使用单个字符C ++评估if语句

时间:2013-10-01 15:45:34

标签: c++ while-loop boolean

我正在尝试评估一个字符:

bool repeat = true;
while (repeat)

//code

char x;
    cout << "Would you like to tansfer another file? Y/N ";
    cin >> x;

    if (x == 'y' || x == 'Y')
        repeat = true;
    if (x == 'n' || x == 'N')
        repeat = false;
    else
        throw "Input error";

我一直在输入错误作为我的控制台输出。有什么想法吗?我不能让while循环重复。

2 个答案:

答案 0 :(得分:6)

您在这里缺少else

if (x == 'n' || x == 'N')

应该是:

else if (x == 'n' || x == 'N')

您需要在while之后添加大括号以包含输入和if语句。

答案 1 :(得分:4)

您在{}之后忘记了大括号while

while (repeat)
{

  char x;
  cout << "Would you like to tansfer another file? Y/N ";
  cin >> x;

  if (x == 'y' || x == 'Y')
      repeat = true;
  else
  if (x == 'n' || x == 'N')
      repeat = false;
  else
      throw "Input error";

}