如果用户选择1或2,则功能无法运行。有什么建议么?
#include <iostream>
using namespace std;
void getTitle();
void getIsbn();
int main()
{
int choice = 0; // Stores user's menu choice
do
{
// Display menu
cout << " Main Menu\n\n\n";
// Display menu items
cout << " 1. Choose 1 to enter Title.\n";
cout << " 2. Choose 2 to enter ISBN.\n";
cout << " 3. Choose 3 to exit.\n";
// Display prompt and get user's choice
cout << " Enter your choice: ";
cin >> choice;
// Validate user's entry
while (choice < 1 || choice > 3)
{
cout << "\n Please enter a number in the range 1 - 3. ";
cin >> choice;
}
switch (choice)
{
case 1:
getTitle();
break;
case 2:
getIsbn();
break;
}
} while (choice != 3);
return 0;
}
void getTitle()
{
string title;
cout << "\nEnter a title: ";
getline(cin, title);
cout << "\nTitle is " << title << "\n\n\n";
}
void getIsbn()
{
string isbn;
cout << "\nEnter an ISBN: ";
getline(cin, isbn);
cout << "\nISBN is " << isbn << "\n\n\n";
}
最佳答案
这些函数当然应该被调用。但是,将发生的是,当您按“ Enter”键键入数字时生成的换行符将由getline()
返回,并且该函数将返回而不会真正提示您。您需要清除该换行符。您可以使用ignore()
来执行此操作:读入cin.ignore();
后立即添加choice
以忽略一个字符。