我的问题是,我试图做一个菜单作为我的程序的一部分。有输入的条件语句,我的else
语句应该说输入无效,并等待输入(以便让用户知道他们输入了一些无效的内容)。为什么当我输入一个char时,这个特定的cin.get()语句在C++中不起作用?
这是相关的片段,以及我的尝试:
void main_menu() {
int opt;
system("CLS");
std::cout << "Main Menu" << std::endl;
std::cout << "\n\nWhat would you like to do?" << std::endl;
std::cout << "1) Fight" << std::endl;
std::cout << "2) Store" << std::endl;
std::cout << "3) Exit" << std::endl;
std::cin >> opt;
std::cin.ignore();
if (opt == 1) {
return main_menu();
}
else if (opt == 2) {
return main_menu();
}
else if (opt == 3) {
return;
}
else {
system("CLS");
std::cout << "Invalid!" << std::endl;
std::cin.get(); //error, but not seen in list or console
}
}
int main() {
main_menu();
return 0;
}
我似乎什么已经搞砸了的上是else
。当我运行它时,代码似乎通过了我设置的std::cin.get()
。
我想要的输出:
Input = 1 // valid input
go to statement 1 (empty for time being.)
Input = 6 // invalid, but is handled with the else:
cout << "Invalid!" << ....
//pause
Input = 'a' //invalid, should be like above:
cout << "Invalid!" << ....
//pause // in reality, it passes
我已经尝试了一些方法,看着比SO其他网站的一些职位(见张贴Why is the Console Closing after I've included cin.get()?)(我曾尝试cin.ignore()
后cin >> var
方法已经不灵) ,但没有工作。
它确实有关换行符等的说法,但我不明白。有人可以解释尾随的换行符是如何工作的,为什么我的代码段不工作?
编辑:cin.get()
的其他陈述已在我的实际代码中工作。
编辑:我试着输入一个数字以外的无效选项,但它没有工作(比如字符)。 Nums虽然工作。所以现在的问题是如何处理除int,float,double等数据类型。
'opt'是'int'类型,是不是? –
是的,我已经从链接文章中读到它可能是来自int输入的尾随换行符。 –
做'std :: cout <<(int)std :: cin.get();',那么你可以看到什么字符被读取。如果您在 –