[Solved] Scan input from file line by line [closed]


If you’re going to do this with fscanf, you want to use a scan set conversion, like:

int a, b;
char c[256];

fscanf(infile, "%d %d %[^\n]", &a, &b, c);

To scan all the lines in the file, you’d do something like:

while (3 == fscanf(infile, "%d %d %[^\n]", &a, &b, c))
    process(a, b, c);

fscanf returns the number of items it converted successfully, so the 3 == is basically saying: “as long as you convert all three items successfully, process them”.

In C++, however, I’d prefer to use an iostream, something like:

infile >> a >> b;
std::getline(infile, c);

Usually, a line a file like this will signify some sort of logical record that you probably want to put into a struct though, so you’d start with that:

struct foo { 
    int a, b;
    std::string c;
};

..then you could overload operator>> to read that entire struct:

std::istream &operator>>(std::istream &is, foo &f) { 
    is >> f.a >> f.b;
    std::getline(is, f.c);
    return is;
}

From there, reading the structs into (for example) a vector could look something like this:

std::vector<foo> vf;

foo temp;

while (infile >> temp)
    vf.push_back(temp);

If you prefer (I usually do) you can remember that a vector has a constructor that takes a pair of iterators–and that std::istream_iterators will work fine for the job, so you can do something like this:

std::vector<foo> vf {
     std::istream_iterator<foo>(infile),
     std::istream_iterator<foo>() };

…and the vector will initialize itself from the data in the file.

1

solved Scan input from file line by line [closed]