lundi 23 février 2015

How do you parse an input file to tell you which code to run?

The input file is structured as:



1 data + integer


1 data - integer


2 integer + data


3 data - data


4 data <= data


4 data == data


4 data > data



so that the the number on the front of each line tells you how to parse it. my code that specifically handles the input file is:



ifstream infile("test.txt");
int command = 0;
Data tempdata1, tempdata2;
int tempint = 0;
string s;
while(!infile.eof())
{
infile >> command; //should read the first int of each line
to determine how to handle the data
switch(command)
{
case 1:
infile >> tempdata1;
infile >> s;
infile >> tempint;

/*handle the data and int according to if s is + or - */
break;

case 2:
infile >> tempint;
infile >> s;
infile >> tempdata1;

/*handle the data and int according to if s is + or - */
break;

case 3:
infile >> tempdata1;
infile >> s;
infile >> tempdata2;

/*handle the data and data according to if s is + or - */
break;
case 4:
infile >> tempdata1;
infile >> s;
infile >> tempdata2;

/*handle the data and data according to if s
is <=, <, ==, >=, or !=, etc */
break;
}

}


I have a class to handle these data types, with their operators overloaded. The code I have so far worked for the first 3 lines of my input file, but then it thought that 3 was 2 and treated it as a case 2. I also noticed that when I made the input file only 2 lines long, it looped through it 3 times.


My concise questions are:




  1. Is there a better way to parse this type of input file?




  2. Any ideas why the code mistreats some cases?




Aucun commentaire:

Enregistrer un commentaire