【问题标题】:Evaluating if statement with single char C++用单字符 C++ 评估 if 语句
【发布时间】:2013-10-01 15:45:34
【问题描述】:

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

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 循环重复。

【问题讨论】:

    标签: c++ while-loop boolean


    【解决方案1】:

    您在这里缺少else

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

    应该是:

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

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

    【讨论】:

      【解决方案2】:

      你在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";
      
      }
      

      【讨论】:

        猜你喜欢
        • 2011-12-22
        • 1970-01-01
        • 1970-01-01
        • 2010-12-01
        • 2016-05-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-08
        相关资源
        最近更新 更多