逐行扫描文件输入

时间:2015-11-12 21:39:39

标签: c++ scanf

数据的格式为

int int string

例如

1 2 Hello Hi
2 3 How are you?

如何从中获取单个元素?

1 个答案:

答案 0 :(得分:3)

如果您要使用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>() };

...矢量将从文件中的数据初始化。

相关问题