【问题标题】:String input error [duplicate]字符串输入错误[重复]
【发布时间】:2013-07-21 09:14:32
【问题描述】:

能否再次帮我确定我的代码有什么问题?每次您选择一个案例时,例如您选择“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();
}

【问题讨论】:

  • @JoachimPileborg 我的意思是 getline 语句不起作用

标签: c++


【解决方案1】:

当然结束了,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 之后,流将换行符留在输入缓冲区中,所以当你做 std::getline 它读取该换行符而不是您想要的输入。

您可以像这样删除尾随的换行符:

std::cin >> choice;

// Skip trailing text, up to and including the newline
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')

【讨论】:

  • 我怀疑这是最后的 getch() 的用途,但它在错误的地方。
  • @Barmar 这似乎很常见,例如getch 在最后停止程序退出,直到按下一个键,特别是对于初学者。而getch 不能用于此,因为它绕过了流输入并直接从控制台读取。
  • 啊,有道理。我知道它绕过了流,但我认为这只是另一个初学者错误。
猜你喜欢
  • 1970-01-01
  • 2012-05-23
  • 2018-12-21
  • 1970-01-01
  • 1970-01-01
  • 2012-11-17
  • 1970-01-01
  • 2013-11-22
  • 2020-09-27
相关资源
最近更新 更多