使用流样式从文件中读取一行
我有一个简单的文本文件,其中包含以下内容,
word1 word2
我需要在 C++ 应用程序中读取它的第一行。 以下代码有效,……
std::string result;
std::ifstream f( "file.txt" );
f >> result;
但结果变量将等于“word1”。它应该等于“word1 word2”(文本文件的第一行) 是的,我知道,我可以使用 readline(f, result) 函数,但是有没有办法做到同样的事情,使用 >>风格。这可能会更漂亮。 可能,一些我不知道的操纵器在这里会有用吗?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,定义一个线类并定义运算符>>对于这堂课。
Yes define a line class and define the operator >> for this class.
不,没有。使用 getline(f, result) 读取一行。
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.