moe
moe

Reputation: 735

infile with eof and sentinel

I am reading in a file and have a sentinel in the middle of this .dat file. The first part are variables and the value they are to be assigned. I am getting the variable and their value fine. Here's what I have.

int main() {
ifstream infile;
string variable;
int value;

infile.open("test.dat");

while (infile.peek() != EOF) {

    infile >> variable;
    infile >> value;

}



return 0;
}

and here is the .dat file

f 32
h 3
l -2
q 3
v 5
$
lqv
hfv
vvf
vfl

My first thought is to use to while loops. The was while (variable != "$") but when I do this I get put into an infinite loop. So I am totally lost on how to get and assign variables and then get the rest of the .dat file.

I had to change this a little due to the fact that I don't want to hard code the variables. I will use 2 loops. One before the $ and one after the $. when I try while (infile != "$") I get an infinite loop.

Upvotes: 0

Views: 430

Answers (3)

cpatricio
cpatricio

Reputation: 457

You can check if the next char is '$' or EOF, but after ">>" you need to add a get for the \n.

    ifstream file("test.dat");
    int value;
    string variable;
    while(file.peek() != '$')
    {
            file >> variable;
            file >> value;
            while(file.get() != '\n' && file.good()); // '\n'
            if(!file.good()) break;
    }

This only works if you really know the structure of the file, otherwise you should read line and scan what for what you need.

Upvotes: 0

Thomas Matthews
Thomas Matthews

Reputation: 57718

I suggest the following, read in the first variable name and if necessary read the value:

while (infile >> variable)
{
  if (variable != "$")
  {
    infile >> value;
  }
  else
  {
    break;
  }
}

An std::map is very useful for associating variable names to values:

std::map<std::string, double> dictionary;
while (infile >> variable)
{
  if (variable != "$")
  {
    infile >> value;
    dictionary[variable] = value;
  }
  else
  {
    break;
  }
}

The syntax infile >> variable is a more reliable method to read from a file.

Upvotes: 1

Franck
Franck

Reputation: 1635

You can replace

while (infile.peek() != EOF) {
    infile >> variable;
    infile >> value;
    ...
}

by

while (infile.good()) {
    infile >> variable;
    if (variable != "$" && variable.length() > 0) {
        infile >> value;
        switch (variable[0]) {
            ...
        }
    }
    else
        break;
}

This should avoid infinite loop.

Upvotes: 0

Related Questions