我正在构建一个简单的计算器,如果用户未选择正确的运算符,则尝试进行while循环,因此如果他们未选择+-*/%,则需要将其卡在循环中。我知道如果只为每个符号放置!=,即使使用||,如果不满足第一个条件,它也将继续运行。

这是我的代码,有些帮助将不胜感激。

#include "stdafx.h"
#include <iostream>

using namespace std;

int main()
{
    int a;
    int b;
    int c;
    char symbol;

    cout << "Please choose a number\n" << endl;
    cin >> a;

    cout << "\nPlease choose another number\n" << endl;
    cin >> b;

    cout << "\nPlease choose a operator: +, -, *, /, %,\n";
    cin >> symbol;

    while (symbol != '+', '-', '*', '/', '%')
    {
        cout << "\nPlease choose a VALID operator: +, -, *, /, %,\n";
        cin >> symbol;
    }

最佳答案

首先,正如您指出的,单独检查每个运算符(operator)可能是最简单的。但是,请注意,您希望在那里有一个(&&)运算符,而不是(||)运算符:

while (symbol != '+' &&
       symbol != '-' &&
       symbol != '*' &&
       symbol != '/' &&
       symbol != '%') {
    // code...

另外, string::find 可能更方便:
std::string OPERATORS = "+-*/%";
while (OPERATORS.find(symbol) != std::string::npos) {
    // code...

关于c++ - C++ While循环多项选择条件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30059109/

10-12 03:45
查看更多