I have a text file im supposed to use for input. Each line looks like the following:
+ 23 34
- 16 8
% 50 32
I am supposed to take each line and perform the indicated action with the numbers. Currently my program reads the symbol into a character variable and calls a function that is supposed to do the operation with the numbers.
I am trying to read each number into an individual variable but when i do a cin with the text file the int variable reads both numbers as though they were a single one. I have commented the line that does this. (the 23 34 is stored in the int as 2334 as opposed to 23 which is what i want)
#include <iostream>
#include <iomanip>
#include <fstream>
usingnamespace std;
void doAddition(ifstream &inFile);
char ch;
int num1=0, num2=0;
int main()
{ //open the text file
ifstream inFile;
inFile.open( "math.txt" );
//error if the text file is not found
if( inFile.fail() )
{
cout << "The math.txt input file failed to open";
exit(-1);
}
//read the first character on the line
inFile >> ch;
//loop that enables the program to work with each line until the end of the file
while ( inFile )
{
//switch statement to call each individual function based on the symbol
switch(ch)
{
case'+': doAddition(inFile); //call the addition function if the symbol is a + (other functions will be written later)
}
}
return 0;
}
//addition function that takes the text file as it's argument
void doAddition( ifstream &inFile )
{
//this is supposed to read the first number on the line
inFile>> num1; //this line reads both numbers on the line instead of the single number i want it to.
cout<< num1;
}
You should see that it is in fact reading each value separately, but the while loop at line 29 repeatedly calls the function doAddition() until an inFile error occurs.