Reputation: 129
I'm currently writing a program that needs to except an option then followed by a piece of text if the piece of text. if the text is true then a piece of code executes? At least I think that's how it works, however, the program goes straight to the else and keeps looping because of the initial condition it doesn't ask the another input from the user which is getline() ?
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main() {
fstream gFile;
int choice;
string gb;
do {
cout << "Student Grade Book Info Program....\n";
cout << "\tPlease Select an Option: (1 or 2) \n" << endl
<< "\t1. Review Grades"
<< "\n\t2. Quit"
<< "\n\tChoose: ";
cin >> choice;
switch (choice) {
case 1:
cout << "\n\tPlease Enter the Name of the File you wish to View the Grades for: " << endl;
cout << "\n\tAvailable Grade Books: gradeBook\n" <<
"\tType in the Grade Book you would like to view. ";
getline(cin, gb);
if (gb == "gradeBook") {
cout << "execute code...";
}
else {
cout << "\nError there is no such entry in the system." << endl;
}
case 2:
break;
}
} while (choice != 2);
return 0;
}
Upvotes: 0
Views: 63
Reputation: 3911
this is because the input buffer still contains a newline so this will affect next input in your case getline.
To mix getline with extraction operator ">>" correctly just flush the input buffer yourself:
in your example add:
//cin.sync(); // or
cin.ignore(1, '\n');
add one of the above line right before getline so your code will look like:
cin.ignore(1, '\n'); // flushing the buffer
getline(cin, gb);
Upvotes: 0
Reputation: 118292
cin >> choice;
This will read the number that's entered. However, the number that gets typed in here will be followed by a newline, which operator>>
will not read.
cout << "\n\tAvailable Grade Books: gradeBook\n" <<
"\tType in the Grade Book you would like to view. ";
getline(cin, gb);
And this getline()
will now read the newline that was left over from the prior operator>>
, instead of waiting for the next line of input to be entered.
This is a common mistake: mixing operator>>
and std::getline()
. Although it is possible to use both together, additional steps must be taken to do that correctly. The simplest and the easiest way to read newline-terminated lines of text is to use std::getline()
. That's what it's for. Simply use std::getline()
to always read text input. If you want to parse it as an integer, or something else, construct a std::istringstream
, and parse it.
Upvotes: 1