您是否有特定原因专注于使用文本块而不仅仅是读取值?
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
istringstream inf(" + 42 100");
char op;
int num1, num2;
inf >> op >> num1 >> num2;
cout << "Op: " << op << endl;
cout << "Num1: " << num1 << endl;
cout << "Num2: " << num2 << endl;
// pin the op-char to the first operand
istringstream inf2("-43 101");
inf2 >> op >> num1 >> num2;
cout << "Op: " << op << endl;
cout << "Num1: " << num1 << endl;
cout << "Num2: " << num2 << endl;
return 0;
}
输出
Op: +
Num1: 42
Num2: 100
Op: -
Num1: 43
Num2: 101
如果您想使用保证每行只有一个操作和两个操作数的输入文件来执行此操作,则将是这样的:
ifstream inf(fname);
char op;
int o1, o2;
while (inf >> op >> o1 >> o2)
{
// use your op and operands here.
// switch (op)... etc.
}