0

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?

1
  • Why is getline() not recognizable? Mar 7, 2013 at 2:13

1 Answer 1

4

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.
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.