开发者

Read a line from file, using stream style

开发者 https://www.devze.com 2022-12-17 12:59 出处:网络
I have a simple text file, that has following content word1 word2 I need to read it\'s first line in my C++ application.

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 ?


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);
}


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


You can create a local that only has newlines as whitespace, but that would be a confusing hack. Here is an example doing just that with commas.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号