0

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

1 回答 1

2

当然它结束了,在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')
于 2013-07-21T09:23:05.633 回答