所以我在使用 cin
和 switch
语句时遇到了一些问题。
首先,程序提示输入一个 int
:
cout << "How many registers would you like to use?: ";
cin >> kassor;
稍后,要求用户做出选择:
cout << endl << "Press \"S\" to run the queue simulator and/or make a timestep." << endl;
cout << "Press \"Q\" to quit." << endl << endl;
cout << "Choice: ";
cin >> choice;
switch (choice)
{
case 's':
case 'S':
{
cout << "test";
nya = newCustomers();
break;
}
case 'q':
case 'Q':
{
return 0;
}
}
在这里,'q' 选项可以正常工作,但 's' 选项不能。它“挂起”,好像还在等待输入。我尝试了各种 cin.ignore()
等,但无济于事。
让我困惑的是
switch (choice)
{
case 's':
case 'S':
{
cout << "test";
nya = newCustomers();
break;
不提供任何内容,但提供以下内容:
switch (choice)
{
case 's':
case 'S':
{
cout << "test";
cin.ignore(1024, '\n');
nya = newCustomers();
break;
输出“测试”。
我的主要问题是:问题是 cin
还是 case: s
中的问题?
提前致谢:
最佳答案
看起来函数 newCustomers
在输入 choice
后被一两个杂散字符挂断了。这可以解释为什么 ignore
调用“修复”了问题,这是@TheBuzzSaw 在评论中建议的解决方案。
为了更清楚地看到这一点,改变
cout << "test";
到
cout << "test\n";
或到
cout << "test" << std::endl;
在某些系统上,控制台是行缓冲的,因此在程序写入换行符之前您不会看到任何输出。插入 endl
会刷新输出缓冲区,因此即使后续代码挂起,您也应该会看到该消息。或者将其更改为:
cerr << "test\n";
cerr
更积极地刷新缓冲区,正是因为它用于您不想错过的错误输出。
关于c++ - cin 和 switch 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12094862/