Search code examples
c++fileinputgetline

How to read and process text from a file in this specific way?


I have a question regarding some code to process some names or numbers from a file I'm reading. So the text in the file looks like this:

Imp;1;down;67
Comp;3;up;4
Imp;42;right;87

As you can see , there are 3 lines with words and numbers delimited by the character ';' . I want to read each line at a time, and split the entire string in one line into the words and numbers , and then process the information (will be used to create a new object with the data). Then move on to the next line, and so on, until EOF.

So, i want to read the first line of text, split it into an array of strings formed out of the words and numbers in the line , then create an object of a class out of them. For example for the first line , create an object of the class Imp like this Imp objImp(Imp, 1, down, 67) .

In Java i did the same thing using information = line.split(";")' (where line was a line of text) and then used information[0], information[1] to access the members of the string array and create the object. I`m trying to do the same here


Solution

  • Don't use char array for buffer, and don't use std::istream::eof. That's been said, let's continue in solving the problem.

    std::getline is simmilar to std::istream::getline, except that it uses std::string instead of char arrays.

    In both, the parameter delim means a delimiting character, but in a way that it's the character, which when encountered, std::getline stops reading (does not save it and discards it). It does not mean a delimiter in a way that it will magically split the input for you between each ; on the whole line.

    Thus, you'll have to do this:

    #include <iostream>
    #include <fstream>
    #include <sstream>
    #include <string>
    
    ...
    
    std::ifstream myFile("D:\\stuff.txt"); // one statement
    
    if (myFile.is_open()) {
        std::string line;
    
        while (std::getline(myFile, line)) { // line by line reading
            std::istringstream line_stream(line);
            std::string output;
    
            while (std::getline(line_stream, output, ';')) // line parsing
                std::cout << output << std::endl;
        }
    }
    

    We construct a std::istringstream from line, so we can parse it again with std::getline.