逐行扫描文件中的输入
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
returns 它转换成功的项目数,所以 3 ==
基本上是说:"as long as you convert all three items successfully, process them".
然而,在 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
s 可以很好地完成这项工作,所以你可以这样做:
std::vector<foo> vf {
std::istream_iterator<foo>(infile),
std::istream_iterator<foo>() };
...向量将从文件中的数据初始化自身。
数据格式为
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
returns 它转换成功的项目数,所以 3 ==
基本上是说:"as long as you convert all three items successfully, process them".
然而,在 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
s 可以很好地完成这项工作,所以你可以这样做:
std::vector<foo> vf {
std::istream_iterator<foo>(infile),
std::istream_iterator<foo>() };
...向量将从文件中的数据初始化自身。