【问题标题】:C++ Why does this workC++ 为什么会这样
【发布时间】:2015-06-16 23:19:57
【问题描述】:

我正在使用 Microsoft Visual Studio 2013

我目前有这个 switch 语句:

switch (option)
{
        case 1:
            getline(cin, newname);
            cout << "What would you like your new username to be?\nName: ";
            getline(cin, newname);
            name = newname;
            cout << "\nYour username is now '" << name << "' with your balance being $" << balance << "\n";
            options();
            break;
        case 2:
            cout << "\nOpenning cheat menu\n";
            cheats();
            break;
        default:
            cout << "\nExitting to main title...\n";
            title();
            break;
}

您可以忽略案例 2 和默认值,只是显示以便您知道这些案例有效。 Case 2 和 default 工作得很好,但 case 1 表现得很奇怪。正如您在案例 1 中看到的,我有两个 getline(cin, newname);你可能认为我应该只有一个,但出于某种原因,我需要两个才能让这段代码正常运行。

如果我只有其中一个,代码会跳过用户应该提供的输入。如果我有两个,它可以正常工作。

我问过别人这个问题,他们也不明白,所以:为什么会这样。

【问题讨论】:

  • 在您的getline() 之前添加cin.ignore();。那应该可以解决您的问题。 getline() 将换行符留在输入流中。
  • @Icemanind:不,getline 不会“将换行符留在输入流中”。不过使用ignore 的建议很好。
  • @Icemanind 它读取它但不将其添加到字符串中,而是丢弃它

标签: c++ visual-studio visual-c++ switch-statement


【解决方案1】:

显然您在cin输入缓冲区 中有剩余输入,包括换行符。当您使用除getline 之外的其他输入操作时,就会发生这种情况。它们通常不会消耗输入缓冲区中的所有内容。

可以使用ignore,而不是额外的getline,但更好的是,在您之前输入的地方这样做。

【讨论】:

    【解决方案2】:

    我认为here已经发布了类似的问题。

    您需要使用 cin.ignore() 或 cin.sync() 刷新换行符。

    第一个电话似乎也打错了……

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-15
      • 1970-01-01
      • 2011-06-03
      • 2018-06-08
      相关资源
      最近更新 更多