如何从缓冲区c cin cin次数?

时间:2018-02-15 07:19:51

标签: c++

我给出了一串整数/浮点数和操作数(/,*, - ,+),每个都用空格分隔。示例输入将是" 1 + 2 * 3 - 5.

我试图在字符串上使用cin,以便它读取直到空格并将空间之前的所有内容存储到适当的变量中。这是我的代码,它可以工作,但它只能工作,因为我知道有多少操作数和操作符给它,我需要它可以为任何数量的它们工作。

如果我只是说它" 2 + 3"它仍然认为它需要更多的输入,我不知道如何解决这个问题。如果这个问题令人困惑,我非常抱歉,请提出任何澄清问题,我会尽快回答。

int main()
{
    string input = "";
    float num1 = 0, num2 = 0, num3 = 0, num4 = 0;
    char operator1, operator2, operator3;

    cout << "enter string\n";
    cin >> input;

    num1 = atof(input.c_string());
    cin >> operator1;
    cin >> num2;
    cin >> operator2;
    cin >> num3;
    cin >> operator3;
    cin >> num4;
    cout << "num1 is " << num1 << endl;
    cout << "operator1 is " << operator1 << endl;
    cout << "num2 is " << num2 << endl;
    cout << "operator2 is " << operator2 << endl;
    cout << "num3 is " << num3 << endl;
    cout << "operator3 is " << operator3 << endl;
    cout << "num4 is " << num4 << endl;

    return 0;
}

1 个答案:

答案 0 :(得分:0)

你应该循环,阅读直至失败。例如:

while(1) {
    int num1;
    char operand;
    cin >> num1;
    if (cin.fail()) { break; } // Exit the loop when failing
    cout << "Number: " << num1 << "\n";


    cin >> operand;
    if (cin.fail()) { break; }
    cout << "Operand: " << operand << "\n";
}