如何从缓冲区x cin x次数

how to cin from buffer x amount of times?

本文关键字:cin 次数 缓冲区      更新时间:2023-10-16

我给了我一串整数/浮点数和操作数(/,*, - - , (,每个都被一个空间隔开。示例输入将为" 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 stringn";
    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;
}

您应该循环,读取直到失败。例如:

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