Search code examples
c++stringfileend-of-line

C++ check end of line


I got a problem in C++ where I need to parse a file with multiple lines (random strings with random length) and transform the uppercase characters in lowercase character and store the lines in a vector of strings. I'm trying to parse the file character by character but don't know how to identify the end of a line.


Solution

  • If you really want to parse a line character for character, then you have a lot of work. And, you depend a little bit on your environment. Lines could be terminated with '\n' or '\r' or "\r\n".

    I would really recommend to use a function that has been designed to get a complete line. And this function is std::getline. If your line would not contain white spaces, you could also read a string directly with the extractor operator like this: std::string s; ifstreamVariable >> s;

    To be independent of such behavior, we can implement a proxy class to read complete lines and put this into a std::string.

    The file can be read into a vector, with the proxy class and the range based vector constructor.

    For transforming to lowercase, we will use std::transform. That is very simple.

    Please see the following example code.

    #include <iostream>
    #include <vector>
    #include <algorithm>
    #include <iterator>
    #include <sstream>
    
    std::istringstream testDataFile(
    R"#(Line 0 Random legth asdasdasfd
    Line 1 Random legth asdasdasfd sdfgsdfgs sdfg
    Line 2 Random legth asdasdasfd sdfgs sdfg
    Line 3 Random legth a sddfgsdfgs sdfg
    Line 4 Random legth as sds sg
    )#");
    
    
    class CompleteLine {    // Proxy for the input Iterator
    public:
        // Overload extractor. Read a complete line
        friend std::istream& operator>>(std::istream& is, CompleteLine& cl) { std::getline(is, cl.completeLine); return is; }
        // Cast the type 'CompleteLine' to std::string
        operator std::string() const { return completeLine; }
    protected:
        // Temporary to hold the read string
        std::string completeLine{};
    };
    
    int main()
    {
        // Read complete source file into maze, by simply defining the variable and using the range constructor
        std::vector<std::string> strings{ std::istream_iterator<CompleteLine>(testDataFile), std::istream_iterator<CompleteLine>() };
    
        // Convert all strings in vector ro lowercase
        std::for_each(strings.begin(), strings.end(), [](std::string& s) { std::transform(s.begin(), s.end(), s.begin(), ::tolower); });
    
        // Debug output:  Copy all data to std::cout
        std::copy(strings.begin(), strings.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
    
        return 0;
    }
    

    This is the "more"-C++ way of implementing such a problem.

    By the way, you can replace the istringstream and read from a file. No difference.