Question

I currently have a text file that is as follows:

12 6 4 9 

It is a very simple text file since I want to just get one line working and then maybe expand to multiple lines later. Extra aside: this is for a RPN calculator I am working on.

I want to go through this text file character by character. The way I currently have it implemented is with a simple while loop:

string line;
while (!infile.eof()){
    getline(infile, line);

    if (isdigit(line[0])){
        rpn_stack.push_back(atof(line.c_str()));
    }
}

rpn_stack is a vector since I will not be using the built in stack libraries in C++. The problem I am currently having is that the output is just outputting "12". Why is this?

Is there a way that I can traverse through the file character by character instead of reading as a line? Is it breaking because it finds a white space (would that be considered the EOF)?


EDIT:

The code has been rewritten to be as the following:

string line;

while (!infile.eof()){
    getline(infile, line);

    for (int i = 0; i < line.size(); i++){
        if (isdigit(line[i])){
            rpn_stack.push_back(atof(line.c_str()));
        }
    }
}

The output is 12 5 different times, which is obviously wrong. Not only are there 4 items in the txt document, but only one of them is a 12. Can someone give some insight?

Was it helpful?

Solution

This will read as many doubles from infile as possible (i.e. until the end of file or until it comes across a token that isn't a double), separated by whitespace.

for (double d; infile >> d;)
  rpn_stack.push_back(d);

If you need parse line-by-line, as @ooga says you will need a two-stage reader that looks something like this:

for (std::string line; getline(infile, line);) {

  std::istringstream stream{line};

  for (double d; stream >> d;)
    rpn_stack.push_back(d);
}

Bonus hint: don't use .eof()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top