Read a line from the console

user2757083 picture user2757083 · Mar 10, 2014 · Viewed 11.1k times · Source

I am reading several string such as name , surname , student number and grades, the first three I have done as follows:

 cout<<"Enter the student's first name: "<<endl;
            string name;
            cin>>name;
            cout<<"Enter the student's last name: "<<endl;
            string surname;
            cin>>surname;
            cout<<"Enter the student's unique student number: "<<endl;
            string studentNo;
            cin>>studentNo;

How grades are enter in the following manner : " 90 78 65 33 22" and I want read the entire line of grade into a string variable. All these string are used to construct student object.

How would I achieve this, I tried using getline() but this does not work.

My attempt:

 int main(){

cout<<"Enter the student's first name: "<<endl;
                string name;
                cin>>name;
                cout<<"Enter the student's last name: "<<endl;
                string surname;
                cin>>surname;
                cout<<"Enter the student's unique student number: "<<endl;
                string studentNo;
                cin>>studentNo;
                string classRcd;
               std::getline(cin , classRcd);
               db.add_student( name , surname , studentNo , classRcd); 
    /*Creates a student object and add it to a list in db which is of type database*/
               clear();  //clears the screen in a while loop
  return 0;
}

Answer

DevSolar picture DevSolar · Mar 10, 2014
std::string line;
std::getline( std::cin, line );

There is another getline() that is a member function of the stream; that one is usually not what you want.