如何从缓冲区x cin x次数
how to cin from buffer x amount of times?
我给了我一串整数/浮点数和操作数(/,*, - - , (,每个都被一个空间隔开。示例输入将为" 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";
}
相关文章:
- C++中的cin.ignore()函数不适用于整个流
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- Problems with std::cin.fail()
- 如何在c++中限制尝试次数
- 在映射擦除c++期间执行循环的次数
- 对象实例化调用构造函数的次数太多
- 一个函数,用于查找字符串1包含字符串2 c++的次数
- 使用RAII在给定次数的迭代后重新分配资源
- 由cin中的字符串中未捕获空白引起的分割错误
- 在C++中使用Cin,我如何在1行中输入
- 将 cin 限制为只有一个
- cin >> int 给定一个字符串将 int 赋值为 0
- 查找字符在两个索引之间出现的次数
- istream std::cin如何修改自定义istream缓冲区
- 3-3. 编写一个程序来计算每个不同单词在其输入中出现的次数
- C++ 将 CIN 值存储到任何类型的数组中
- 整数区间(或 int 数组)中每个数字的出现次数
- 如何从缓冲区x cin x次数
- 标准中的反推次数::cin::ungetc