文件I/O c++ ifstream语法

File I/O C++ ifstream syntax

本文关键字:ifstream 语法 c++ 文件      更新时间:2023-10-16

我正在尝试编写一个程序,该程序将读取文本文件并执行它在文本文件中读取的数学操作。

的例子:+ 45 35

我正在使用一个输入流来读取该文本块,并在函数中的数字之前执行一个数学运算。

我找了一个多小时才找到正确的语法,我都快抓狂了。

我完全困在弄清楚如何让流函数读取每个字符,直到空白,但它一次读取一个字符,getline甚至不是一个可识别的函数,我认为这将有助于我的事业。

这是我正在使用的,每次读取一个字符

char ch; 
inFile >> ch;

命令流读取文本块直到它达到空白的正确语法是什么,谁能建议我如何通过将文本文件中的数字加在一起?

是否有一个特定的原因,你是固定使用文本块,而不是在值读取?

#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

如果你想在保证每行只有一个op和两个操作数的输入文件中这样做,它将是这样的:

ifstream inf(fname);
char op;
int o1, o2;
while (inf >> op >> o1 >> o2)
{
    // use your op and operands here.
    // switch (op)... etc.
}