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

C++ 使用流样式从文件中读取一行,c++,stl,stream,C++,Stl,Stream,我有一个简单的文本文件,它有以下内容 word1 word2 我需要阅读它在我的C++应用程序中的第一行。 下面的代码工作 std::string result; std::ifstream f( "file.txt" ); f >> result; 。。。但是,结果变量将等于“word1”。它应该等于“word1 word2”(文本文件的第一行) 是的,我知道,我可以使用readline(f,result)函数,但是有没有一种方法可以使用>>样式实现同样的功能。这可能会更漂亮。

我有一个简单的文本文件,它有以下内容

word1 word2
我需要阅读它在我的C++应用程序中的第一行。 下面的代码工作

std::string result;
std::ifstream f( "file.txt" );
f >> result;
。。。但是,结果变量将等于“word1”。它应该等于“word1 word2”(文本文件的第一行) 是的,我知道,我可以使用readline(f,result)函数,但是有没有一种方法可以使用>>样式实现同样的功能。这可能会更漂亮。
可能的话,一些操纵器,我不知道,在这里会有用吗?

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

您可以创建一个仅将换行符作为空白的本地,但这将是一个令人困惑的破解

是为该类定义线条类并定义运算符>>

#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);
}
#包括
#包括
#包括
结构线
{
std::字符串行;
//添加要转换为字符串的运算符。
//这允许您在std::string所在的任何位置使用line类型的对象
//可以使用(除非构造函数标记为显式)。
//此方法基本上将行转换为字符串。
运算符std::string(){return line;}
};
std::istream&operator>>(std::istream&str,Line&Line)
{
返回std::getline(str,line.line);
}
std::ostream和操作员