pretty basic problem but my C++ is pretty far back

here's my problem

I have to read a text file and parse all the different field

ex:

001 R0S11 182983 2009/02/22 45607
002 R0S12 182983 2009/02/23 45707
003 R0S13 182983 2009/02/16 45807
004 R0S14 182983 2009/02/04 45907
....

once I've read the file I need to parse all the fields within it in order to validate each field based on certain criteria

I figure that once I read the file I would dump all the data in its respective variable

what is the bet way to read the data and extract each field from each line

thanks for any help

Pabs

Recommended Answers

All 2 Replies

Use fgets to read one line, strtok to split each line between spaces, sscanf to break apart each value. Do this all in a loop to read multiple lines.

This is c++, not C. So use c++ ifstream to read the file one word at a time. Is there a need to keep the individual fields with the entire line? If not, then you don't have to keep them in memory, just read the file one word at a time

#include <fstream>
#include <string>
using namespace std;
...
...
ifstream in("in.txt");
std::string word;
while( in >> word )
{
   // do something
}

Or if you need to retain the entire line

#include <fstream>
#include <string>
#include <sstream>
using namespace std;
...
...
ifstream in("in.txt");
string word;
string line;
while( getline(in, line) )
{
    stringstream str(line);
    while( str >> word )
    {
         // do something
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.