I wrote this code. It works in the main function
cout << "Enter the patron's name: ";
getline(std::cin, patron.name);
cout << "Enter the book title: ";
getline(std::cin, book.title);
cout << book.title << " is now checked out to " << patron.name << endl;
However, when I put it under a do while loop with switch case, it does not work anymore.
do {
cout << endl << "? "; cin >> choice;
switch (toupper(choice)){
case 'T':
cout << "Enter the patron's name: ";
getline(std::cin, patron.name);
cout << "Enter the book title: ";
getline(std::cin, book.title);
cout << book.title << " is now checked out to " << patron.name << endl;
break;
}[enter image description here][1]
} while (choice != 'Q' && choice!= 'q');
The input was like:
Could anyone explain to me why this happened? Thanks
After this statement
cout << endl << "? "; cin >> choice;
insert
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
to remove the new line character (that corresponds to the pressed Enter key after the input) that is still in the input buffer, Otherwise a call of getline
will read an empty string.
You should include the header <limits>
to use the class numeric_limits
This \\n
after T(your input) is being consumed by getline. That's why you are getting such behaviour. You need to flush the newline out of the buffer.
You can do this by adding this statement as shown.
std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
cout << "Enter the patron's name: ";
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.