I was doing homework while I encountered this problem. In the menu, I didn't want the menu part to accept anything but an integer, it works but... after putting in an integer it proceeds to still use the error validation from the menu...
Example Scenario:
Enter value : abc
Error! Value must be a proper integer. Enter value again : 1
Enter name : abc
Error! Value must be a proper integer. Enter value again : (this is the part i'm having a problem with
Why is this happening? What is the solution to this?
Don't pass d in. Declare it as a local variable instead.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
void reg(stu *student){
cout << "Enter name : ";
cin.get(student->name, 100);
}
int input() {
int d = 0;
string line;
while (true) {
getline(cin,line);
stringstream ss(line);
if (ss >> d)
break;
cout << "Error! Value must be a proper integer. Enter value again : ";
}
return d;
}
You should use cin.getline() instead of cin.get(). cin.get() leaves the newline in the input stream, so the next getline() call in input() will read a blank line since it hits the newline right away.
cin.getline(student->name, 50); // sizeof name is 50 (not 100)
Or you could make name a string and read it with std::getline():
getline(cin, student->name); // if name is a std::string.