C++/getline()
Expert: vijayan - 5/15/2009
QuestionHi
my question is about the code below.when i run the programme after that i enter nameofcourse why it wants a new line charachter and why it printing the name of course it discards the new line?
#include<iostream>
using std::cout;
using std::cin;
using std::endl;
#include<string>
using std::string;
using std::getline;
class GradeBook
{
public:
void displaymessege(string coursename)
{
cout<<"The name of course is "<<coursename<<endl;
}
};
int main(){
string nameofcourse;
GradeBook myGradeBook;
cout<<"Enter your course:"<<endl;
getline( cin , nameofcourse );
myGradeBook.displaymessege(nameofcourse);
return 0;
}
sorry,i forgot to post the code in previous question
Thanx
Bita
Answerstd::istream& std::getline( std::istream& stm, std::string& str, char delimiter = '\n' ) ;
reads a line from the input stream and stores it into the string. Because the getline() function begins reading at the current file position, it can also be used to read the remainder of a line, or any characters up to the specified delimiter.
The reading of the line involves: extract characters from the input stream one by one and place it in the string till
a. end of file (eof) of the input stream is reached.
b. after the function extracts a character that compares equal to the delimiter. In this case, the delimiter character is not appended to the string; it is also not put back into the stream; it is simply discarded.
So, getline( cin , nameofcourse ) reads characters one by one from cin and places them into nameofcourse till a new line is encountered. The new line is not appended to nameofcourse, but it is extracted from cin and then discarded.