Click to See Complete Forum and Search --> : Help reading input file


tibbs14
April 17th, 2003, 12:00 PM
I am trying to read an input file by inputing them directly into containers. This works up until the point where there is a new line and I have to go to the next. Here is the input file:


P1 15 32 95 51
P2 99 5
P1 16 92 34 77 99
P2 Finish


Ahead of time I dont know how many numbers will be following the P?. So far I loop through and grab each of the numbers with a line like this:


file >> inputNum;


When it runs out of numbers, inputNum becomes 0. Now I need to get to the next line and start with inputing a string "P2" and then start inputing integers again. How do I get to the next line? If I keep trying to input stuff it keeps giving me 0.

Here is my code reduced to show the important parts:


while( !file.eof() )
{
file >> process;

process[0] = '0';

temp->process = atoi( process );

while( inputNum != 0 )
{
file >> inputNum;

if( inputNum < 1 )
{
break;
}

}

}

Philip Nicoletti
April 17th, 2003, 12:27 PM
I'm not eaxctly sure what you are doing, but one way
might be to read line by line into a string, put
the string into a stringstream, and process it.

Here is an example :

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
ifstream file("lines.txt");
if (!file)
{
cout << "problem with file open" << endl;
return 0;
}

string line;
while (std::getline(file,line))
{
istringstream iss(line);
string tag;

iss >> tag;

cout << tag << endl;

int value;
while (iss >> value)
{
cout << " " << value << endl;
}
}

return 0;
}