c++ - cin 和 switch 奇怪的行为

标签 c++ switch-statement cin

所以我在使用 cinswitch 语句时遇到了一些问题。 首先,程序提示输入一个 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/

相关文章:

c++ - Eclipse Oxygen 和 org.eclipse.jface 给出 NullPointerException 对话框

swift - 如何更正此 Swift 枚举?

C++:如何使用cin和file两种方式获取输入?

c++ - 协助使用基于 C++ 的基本 GPA 计算器和 cin 用法

c++ - 防止不必要的 C++ 仿函数对象复制

c++ - 找不到 -lfl 的库

xcode - 不知道为什么switch控件总是发送false值

c++ - 开关无外壳

c++ - 当一长串字符传递给第一个时,为什么在第二个 cin 上不暂停输入?

c++ - 我在 visual studio 的调用堆栈上看到的这些十六进制字符串是什么