Ok, I've asked something similar before, but I still have not been able to understand this... so I just want to have a txt file with math operations in it. Basically, it's just integers multiplies and added. Nothing else.


Each line can contain any multiplication or addition. The code below is the one I want to use to read it from the text file and process it. As you can see, it's stored in the variable "line". Obviously, I have to get the data out of line in order to do whatever with it - to solve it, check for errors.. etc. How do I do this? From reading, I get the impression I can use a global variable, call it calculation or whatever, and then look through each line and is gonna calculate this for me? I think you gotta have it look for the * and the + and then tell the code how to solve it... ? I am not understanding how to extract the data from "line". The global variable idea was just something someone told me I could do. I don't know.
I will need something like this in the future.. read from text file and append result to a text file, so I need to fully understand it. I also looked into tokens.. but I think there are better ways. I like the way it's being done here with getline.. so I do prefer going this route and just extract the input from line.

/* Open the input file & check that it opened OK */
std::ifstream inFile("file1.txt", std::ios::in);
if ( ! inFile.is_open() ){
std::cerr << "Error: unable to open file for input" << std::endl;
return 1;

/* Open the output file & check that it opened OK */
std::ofstream outFile( "file2.txt", std::ios::app ); // Open with append flag
if ( ! outFile.is_open() ){
std::cerr << "Error, unable to open file for output" << std::endl;
return 2;

/* Read from the input and append to the output file */
while ( inFile.good() ){
std::string line;
getline( inFile, line

outFile << line << std::endl; // Write the file to the output file

(by ravenous)

Edited by XodoX: n/a

5 Years
Discussion Span
Last Post by Anirudh Rb

You want to know how to extact the operators and operands from the string variable right?

To do it iterate through every character in the string and check if it is a numeric digit. If it is, store it in a character variable and subtract the character '0' from it. The code is:

int digit;

if(ch >= '0' && ch <= '9')
  digit = ch - '0'; //Do whatever you want to do with the digit now.

How this works can be explained on the basis of ASCII codes of the characters. But, that's another story!

Edited by Anirudh Rb: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.