A. Mittal A. Mittal - 2 months ago 6
C++ Question

How to read first line of file word by word and other lines as line by line store in variables?

A file has contents in format like this

 
3 3
ABCD
ABCD
ABCD
...


I want to read first number in variable k and another number in another variable say n. Rest of the lines I want to store in a string say seq so that

k = 3
n = 3
seq = ABCDABCDABCD..


I need to do this in c++. I just started learning c++. I know how to read file line by line and word by word but I don't know how to read file in this specific format.

Answer

When performing per-line validation, use a std::istringstream to separate the lines, then perform regular stream operations.

For example, given a program taking your input file as the sole argument:

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

int main(int argc, char *argv[])
{
    if (argc < 2)
        return EXIT_FAILURE;

    std::ifstream inp(argv[1]);

    // first line
    std::string line;
    if (std::getline(inp, line))
    {
        // load into string stream for parsing.
        std::istringstream iss(line);
        int k, n;
        if (iss >> k >> n)
        {
            // remaining lines dumped into seq
            std::string seq;
            while (std::getline(inp, line))
                seq.append(line);

            // TODO: use k, n, and seq here
        }
        else
        {
            std::cerr << "Failed to parse k and/or n\n";
        }
    }
    else
    {
        std::cerr << "Failed to read initial line from file\n";
    }
}

It may seem overkill to string-stream the first line, but if your input format mandates this:

k n
data1
data2
etc...

you want to detect when something like this happens:

k
n
data1
...

If that detection isn't important, then you can just pull the first two values directly from the input file stream and ignore the rest of the remaining line to start up the line-append loop. Such code would look like this:

#include <iostream>
#include <fstream>
#include <string>
#include <limits>
#include <cstdlib>

int main(int argc, char *argv[])
{
    if (argc < 2)
        return EXIT_FAILURE;

    std::ifstream inp(argv[1]);

    // read two integers
    int k, n;
    if (inp >> k >> n)
    {
        // ignore the remainder of the current line to position the first
        //  line for our seq append-loop
        inp.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

        std::string line;
        std::string seq;
        while (std::getline(inp, line))
            seq.append(line);

        // TODO: use k, n, and seq here
    }
    else
    {
        std::cerr << "Failed to parse k and/or n\n";
    }
}
Comments