You are here:



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?


using std::cout;
using std::cin;
using std::endl;


using std::string;
using std::getline;

class GradeBook
  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 );


  return 0;


sorry,i forgot to post the code in previous question


std::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.


All Answers

Answers by Expert:

Ask Experts




my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.


about 15 years or so

post graduate engineer

©2016 All rights reserved.