Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a line from file, using stream style

Tags:

c++

stream

stl

I have a simple text file, that has following content

word1 word2

I need to read it's first line in my C++ application. Following code works, ...

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

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

like image 386
AntonAL Avatar asked Oct 20 '25 04:10

AntonAL


2 Answers

Yes define a line class and define the operator >> for this class.

#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);
}
like image 118
Martin York Avatar answered Oct 21 '25 18:10

Martin York


No, there isn't. Use getline(f, result) to read a line.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!