Question

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;
}
Was it helpful?

Solution 2

You still have a new line in the stream after cin>>studentNo, which is giving you an empty string for the classRcd.

You could solve it by just adding another getline() call after cin>>studentNo and leaving alone the result, or ignore the new line by std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

OTHER TIPS

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.

I would suggest using getline(). It can be done in the following way:

#include <iostream>
#include <string>
using namespace std;

int main() 
{
  cout << "Enter grades : ";
  string grades;
  getline(cin, grades);
  cout << "Grades are : " << grades << endl;
  return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top