I am trying to use a getline function in the following code, however it just enters an indefinite loop. Should I enter 1, it will then jump to the another iteration of the loop and ask for my menu choice again, rather than asking for my name.
Does anyone have any idea where I'm going wrong?
#include <iostream>
#include <string>
#include <ncurses.h>
using namespace std;
// DECLARE
void menu();
void menu_act_on_choice();
void string_function();
// CODE
void menu_act_on_choice(int choice_in) {
switch (choice_in) {
case 1:
string_function();
break;
default:
break;
}
}
void string_function() {
string user;
cout << "Enter your first and last: ";
getline(cin, user);
cout << user << endl;
}
void menu() {
int choice = 0;
do {
cout << "1. String functions" << endl;
cout << "2. Array functions" << endl;
cout << "3. Exit" << endl;
cout << "Enter choice: ";
cin >> choice;
menu_act_on_choice(choice);
} while(choice != 3);
}
//EXECUTE
int main() {
menu();
}
When you enter the menu choice which is read by
cin >> choice;
you ended that with the Enter key right?
That Enter key will be added to the input buffer as a newline. But cin >> choice
will not read it, instead that happens with the getline
call which reads it as an empty line.
The simple solution is to ignore all input until (and including.) the newline after getting the menu choice.
cin >> choice;
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Add cin.ignore();
before getline line.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.