请问您能帮助我再次确定我的代码中的错误吗?每次选择一个案例时,例如你选择了“1”这是“NBA球员”,并且你被问到谁是你最喜欢的球员,一旦你输入你的答案,程序就会结束。我认为问题出在我的getline声明中,但我无法确定它。
#include<iostream>
#include<conio.h>
#include<string>
using namespace std;
int main()
{
int choice;
string nbaPlayer;
string tele;
string food;
string subject;
string x;
cout << "This program determines your favorites.\n\n";
cout << "Please select the number of your corresponding choice.";
cout << "\n1. NBA Player";
cout << "\n2. Teleserye";
cout << "\n3. Food";
cout << "\n4. Subject";
cout << "\n5. Exit";
cin >> choice;
switch (choice)
{
case 1:
cout << "You have chosen NBA Player.\n";
cout << "Please enter your favorite NBA Player. \n";
getline(cin, nbaPlayer);
cout << "Your favorite NBA player is " << nbaPlayer;
break;
case 2:
cout << "You have chosen Teleserye.\n";
cout << "Please enter your favorite teleserye. \n";
getline(cin, tele);
cout << "Your favorite teleserye is " << tele;
break;
case 3:
cout << "You have chosen food.\n";
cout << "Please enter your favorite food. \n";
getline(cin, food);
cout << "Your favorite food is " << food;
break;
case 4:
cout << "You have chosen subject.\n";
cout << "Please enter your favorite subject. \n";
getline(cin, subject);
cout << "Your favorite subject is " << subject;
break;
case 5:
cout << "You chose to exit.\n";
break;
default:
cout <<"\nInvalid input";
}
getch();
}
答案 0 :(得分:2)
当然它结束了,在switch
声明后,没有什么可以继续该程序。
您可能需要围绕输出循环switch
:
bool go_on = true;
while (go_on)
{
// Output menu...
// Get choice
switch (choice)
{
// All other cases...
case 5:
go_on = false; // Tell loop to end
break;
}
}
哦,似乎你的问题是你得到一个空行......这是因为在你得到choice
之后,流在输入缓冲区中留下了换行符,所以当你做{{1它会读取换行符而不是您想要的输入。
您可以删除这样的尾随换行符:
std::getline