简体   繁体   中英

File I/O C++ ifstream syntax

I am attempting to write a program that will read a text file and perform the mathematical operations that it reads in the text file.

Example: + 45 35

I am using an input stream to read that block of text and perform a mathematical operation that precedes the numbers in a function.

I have looked for over an hour for the right syntax and I'm about to tear my hair out.

I am completely stuck in figuring out how to get the streaming function to read every character until the whitespace but it reads one character at a time and getline is not even a recognizable function which I thought would help my cause.

This is what I'm using which reads one char at a time

char ch; 
inFile >> ch;

What is the correct syntax to command the instream to read a block of text until it reaches whitespace, and could anyone suggest how would I go by adding the numbers together from the text file?

Is there a specific reason you're fixated on using a block of text rather than just reading in the values?

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

Output

Op: +
Num1: 42
Num2: 100
Op: -
Num1: 43
Num2: 101

If you want to do this with an input file guaranteed to have only an op and two operands per line it would be something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM