Reputation: 2009
I have an issue with the code in line 23. (Please see code below)
When I use "cin >> studentNum"; I have no issue and the program reads the one string for the firstname, but if I want to gather more data using "getline(cin, studentNum)" to read more strings like the full name, the program just skips the command and asks for the score .
Why is that?
#include <iostream>
#include <string>
using namespace std;
int main()
{
int studentNum, testNum, i, j;
double sum, testScore, average;
string studentName;
i = 0;
// asking user for input
cout << "Please enter the number of students in this classroom: " << endl;
cin >> studentNum;
cout << "Now enter the number of tests each student has taken in this class: " << endl;
cin >> testNum;
while (i < studentNum)
{
cout << endl << "Now please enter the firstname of the student: " << endl;
cin >> studentName; //**My Problem is in this line ###########**
j = 0;
sum = 0;
while (j < testNum)
{
cout << "Please enter the score of each test, then hit enter: " << endl;
cin >> testScore;
sum += testScore;
j++;
}
i++;
}
}
Upvotes: 0
Views: 73
Reputation: 644
You should clear the state flag and flush the steram
cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
getline(cin, studentName);
Upvotes: 1
Reputation:
It sounds to me that you need to use cin.ignore
. You need to discard the linefeed character still present in the stream.
#include <limits>
// This is not a C++11 feature, works fine in C++98/03
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::getline(std::cin, studentName);
By default, operator>>
will skip leading whitespace, i.e. classifed by std::ctype
. You can see that in a test program by turning this behavior off with unsetf(std::ios_base::skipws)
, that it will extract the whitespace. By using cin.ignore
, you can simply discard it since it's undesirable. For more information, see cin and getline skipping input.
Upvotes: 2