Reputation:
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;
}
Upvotes: 4
Views: 28217
Reputation: 7990
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');
Upvotes: 3
Reputation: 1071
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;
}
Upvotes: 3
Reputation: 70263
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.
Upvotes: 5