输入任何内容后,我的代码输出无效

时间:2019-05-13 17:45:10

标签: c++

我正在尝试使用C ++创建一个随机数生成器。我希望随机数生成器能够生成十进制数或整数,具体取决于用户选择的内容。我已经编码到系统选择随机整数的位置(如果用户选择了整数)。我的问题是,当用户输入任何内容(包括选项之一)时,它仍然输出无效。

我已经仔细检查了几次代码,试图找出问题所在。我是编码的新手,所以我可能错过了一些东西。

#include <iostream>
#include <cstdlib>
#include <string>

int main() {
  int whole_number;
  double decimal_number;
  std::string user_input = "invalid";
  std::string yes_or_no = "invalid";
  whole_number = 0;
  decimal_number = 0;
  double dec1 = 0;
  int wh1 = 0;
  std::cout << "\n1-100 RANDOM NUMBER GENERATOR\n";
  label1:
  std::cout << "\n\nType what kind of random number you want to generate:\n\n";
  std::cout << "Type whole number to generate a whole number\n";
  std::cout << "Type decimal number to generate a decimal number\n";
  label3:
  std::cin >> user_input;
  if (user_input == "whole number") {
      std::cout << "You have selected: whole number\nWould you like to pick again?\nyes/no\n";
      goto label2;
  }
  else if (user_input == "decimal number") {
      std::cout << "You have selected: decimal number\nWould you like to pick again?\nyes/no\n";
      goto label2;
  }
  else {
      std::cout << "\nInvalid, try again.\n\n";
      goto label3;
  }
  label2:
  std::cin >> yes_or_no;
  if (yes_or_no == "yes") {
      goto label1;
  }
  else if (yes_or_no == "no") {
      goto label4;
  }
  label4:
  if (user_input == "whole number") {
      wh1 = rand() % 100 + 1;
  }
}

我希望代码继续前进到询问您是否要重新输入选择的位置,但是它将输出以下内容:

无效,请重试。

无效,请重试。

1 个答案:

答案 0 :(得分:2)

>>的{​​{1}}运算符最多读取第一个空格字符。因此,您只会看到“整数”或“十进制”,这与您要检查的内容不匹配。

我建议改用getline()。它将读取整行输入。