Victor Martins - 9 months ago 34
C++ Question

# Why is the program looping instead of it asking for input?

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
<< "\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;
"\tType in the Grade Book you would like to view. ";

getline(cin, gb);

cout << "execute code...";

}
else {
cout << "\nError there is no such entry in the system." << endl;

}

case 2:
break;
}

} while (choice != 2);

return 0;
}


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.