使用流样式从文件中读取一行

时间:2010-01-15 02:42:16

标签: c++ stl stream

我有一个简单的文本文件,其中包含以下内容

word1 word2

我需要阅读它在我的C ++应用程序中的第一行。 以下代码有效,......

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

...但结果变量将等于“word1”。它应该等于“word1 word2”(文本文件的第一行) 是的,我知道,我可以使用readline(f,result)函数,但有没有办法做同样的事情,使用>>样式。这可能会更漂亮。 可能的,一些操纵者,我不知道,在这里会有用吗?

3 个答案:

答案 0 :(得分:4)

是定义一个行类并定义运算符>>为了这堂课。

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

答案 1 :(得分:2)

不,没有。使用getline(f, result)读取一行。

答案 2 :(得分:0)

你可以创建一个只有新行作为空格的本地,但这将是一个混乱的黑客。 Here is an example doing just that with commas.