Read line from file using stream style

I have a simple text file having the following content

word1 word2

I need to read it on the first line in my C ++ application. After running the code ...

std::string result;
std::ifstream f( "file.txt" );
f >> result;

... but the result variable will be equal to "word1". It should be equal to "word1 word2" (the first line of the text file) Yes, I know that I can use the readline (f, result) function, but is there a way to do the same using the → style. It can be much prettier. Perhaps some manipulators that I don't know about will be useful here?

+3
source share
3 answers

No no. Use getline(f, result)to read lines.

+2

→ .

#include <string>
#include <fstream>
#include <iostream>


struct Line
{
    std::string line;

    // Add an operator to convert into a string.
    // This allows you to use an object of type line anywhere that a std::string
    // could be used (unless the constructor is marked explicit).
    // This method basically converts the line into a string.
    operator std::string() {return line;}
};

std::istream& operator>>(std::istream& str,Line& line)
{
    return std::getline(str,line.line);
}
std::ostream& operator<<(std::ostream& str,Line const& line)
{
    return str << line.line;
}

void printLine(std::string const& line)
{
    std::cout << "Print Srting: " << line << "\n";
}

int main()
{
    Line    aLine;
    std::ifstream f( "file.txt" );
    f >> aLine;

    std::cout << "Line: " << aLine << "\n";
   printLine(aLine);
}
+4

You can create a local one that only has newlines as whitespace, but that will be a confusing hack. Here is an example that does this with commas.

0
source

Source: https://habr.com/ru/post/1728557/


All Articles