逐行扫描文件中的输入
Scan input from file line by line
数据采用格式
int int string
例如
1 2 Hello Hi
2 3 How are you?
如何从中获取单个元素?
如果要使用fscanf
执行此操作,则需要使用scan set
转换,例如:
int a, b;
char c[256];
fscanf(infile, "%d %d %[^n]", &a, &b, c);
要扫描文件中的所有行,您需要执行以下操作:
while (3 == fscanf(infile, "%d %d %[^n]", &a, &b, c))
process(a, b, c);
fscanf
返回它成功转换的项目数,所以3 ==
基本上是说:"只要你成功转换了所有三个项目,就处理它们"。
然而,在C++中,我更喜欢使用iostream,比如:
infile >> a >> b;
std::getline(infile, c);
通常,像这样的文件中的一行表示某种逻辑记录,您可能想将其放入struct
中,所以您应该从以下内容开始:
struct foo {
int a, b;
std::string c;
};
那么您可以重载operator>>
来读取整个结构:
std::istream &operator>>(std::istream &is, foo &f) {
is >> f.a >> f.b;
std::getline(is, f.c);
return is;
}
从那里,将结构读取到(例如)向量中可能看起来像这样:
std::vector<foo> vf;
foo temp;
while (infile >> temp)
vf.push_back(temp);
如果你喜欢(我通常是这样做的),你可以记住vector
有一个接受一对迭代器的构造函数,而std::istream_iterator
可以很好地完成这项工作,所以你可以做这样的事情:
std::vector<foo> vf {
std::istream_iterator<foo>(infile),
std::istream_iterator<foo>() };
并且矢量将根据文件中的数据对其自身进行初始化。
相关文章:
- 用c++从输入文件中读取另一行
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 获取通过重定向传入的输入文件的名称?
- C++ 如何打开带有另一个目录的输入文件?
- C++模板编程设计问题 - 根据输入文件返回不同的类型
- 如何从输入文件 c++ 创建随机名称生成器
- 从输入文件修剪空格
- 链接器输入文件未使用,因为链接未完成,我无法获得.o
- 我正在尝试从输入文件中读取,然后使用它们的子字符串比较字符串的特定部分
- 我遇到使用 c++ 逐行读取输入文件的问题
- 使用重定向命令从 stdin 读入的字符串"<"输入文件未正确附加
- 使用 getline 从输入文件打印时如何忽略空白行
- 如何按升序对输入文件中的数字进行排序,并找到它们的范围和中值
- 数组大小由输入文件中的行数定义
- 从C++输入文件读取
- 在课堂上创建了一个朋友,给出"无输入文件"错误
- 通过显示一行星号来创建条形图,该条形图将读取数据的输入文件
- 利用输入文件中的数据(字符串和int)并在循环中利用
- C++ 仅读取输入文件中的部分(不是全部)数据以添加到记录中
- 如何从输入文件中读取字符并将其存储到向量中?