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 に答える