Hi guys:
I am very very new in C++. In school they required me to write a program that reads the names of the students registered for a class and output that result in a file. I got almost everything done. The only problem is with the function getline. I know that the problem is there because as soon as I change to a cin method (of course, then I can only enter a name without the lastname) the problem work all right. The things is that the loop starts by the second iteration (that is it asks the user for the second name and skip the first). In the output file I can better see the result: for some reason the first iteration does not work. My question, what happen with the getline function?
note:I know this program is very very simple for all of you. But this is the one my teacher wants me to write. That is, using what I have used. I cannot use anything else. Therefore, please, don't reply me saying that I have to use a pointer or an array;I just can't ! Thanks

#include <iostream>
#include<string>
#include<fstream>

using namespace std;

int main ()
{
 ofstream outstream;
 string name;
 int limit, counter =1;

 outstream.open("c:students.txt");

 cout<<" How many students may register for this class? : ";
 cin>>limit;
 cout<<endl;

 if (limit>0)
  while(counter<=limit)
   {
	   cout<<" Enter the student's name: "<<flush;
	   getline(cin,name);
	   cout<<endl;
	   outstream<<" Student # "<<counter<<" "<<name <<endl;
	   counter++;
	   
   }
 
 else
	 cout<< " You have not entered a valid number.\n ";

   cout<< "The program is complete.\n";

  

   return 0;


}

cin is whitespace delimited, getline is not. A newline is whitespace too. To get rid of an "unwanted" newline, you may consider reading an extra character using the .get() member function.

Checking the return values of these input functions is always prudent.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.