【发布时间】:2011-11-18 14:48:42
【问题描述】:
作为我的学习,我正在尝试使用 c++ ifstream 及其运算符>> 使用下面的代码从文本文件中读取数据。文本文件 outdummy.txt 有以下内容:
just dummy
Hello ofstream
555
我的问题是如何将文件中存在的 char 数据读入 char 数组或字符串。如何在下面的代码中使用 ifstream::operator>> 来做到这一点。
#include <iostream>
#include <fstream>
int main()
{
int a;
string s;
char buf[100];
ifstream in("outdummy.txt",ios_base::in);
in.operator>>(a); //How to read integer? How to read the string data.??
cout << a;
in.close();
getchar();
return 0;
}
【问题讨论】:
-
你的例子是错误的;你甚至没有“正确读取整数”。事实上,那行失败了,
a没有改变,但由于某种原因你已经将它初始化为期望值,所以你自己蒙上了眼睛。 -
@Kerrek 是对的。他是provided 正确且易于使用的解决方案——
getline和string。 -
为什么是
char[]?为什么不std::string? -
@jonsca:我的评论主要是修辞。 :)