【问题标题】:Counting the number of data points in a line from ifstream从 ifstream 计算一行中的数据点数
【发布时间】:2016-10-06 10:48:15
【问题描述】:

我有一堆数据文件需要读入到某个多维容器中,所有这些文件的格式如下:

a1,a2,a3,...,aN,
b1,b2,b3,...,bN,
c1,c2,c3,...,cN,
................
z1,z2,z3,...,zN,

我知道from this previous question 可以通过以下方式快速计算文件中的总行数:

std::ifstream is("filename");
int lines = std::count(std::istreambuf_iterator<char>(is), std::istreambuf_iterator<char>(), '\n');

这让我知道 z,要读入的数据集的总数,每个数据集包含 N 个数据点。下一个挑战是计算每行数据值的数量,为此我可以执行以下操作:

std::ifstream is("filename");
std::string line;
std::getline(is, line);
std::istringstream line_(line);
int points = std::count(std::istreambuf_iterator<char>(line_), std::istreambuf_iterator<char>(), ',');

我可以确信每个文件的每行具有相同数量的数据值。我的问题是,是否有更好/更快的方法来实现上述目标,而无需使用 getline 并将单行转储到字符串中?我想知道这是否可以通过流缓冲区来实现,但是做了一些搜索后我还不太清楚。

任何帮助将不胜感激,谢谢!

【问题讨论】:

  • 对我来说看起来不错。你遇到过什么问题吗?它不符合您的性能要求吗?对于您在这里实际寻求的“帮助”,这是非常开放的。如果我是你,我会对你迄今为止所做的一切微笑,然后继续你项目中的下一个任务。

标签: c++ file-io stl stream ifstream


【解决方案1】:

如果你被要求使用

int points = std::count(std::istreambuf_iterator<char>(line_), std::istreambuf_iterator<char>(), ',');

对于每一行文字,我建议你寻找一种方法来提高效率。

但是,你说:

我可以确信每个文件的每行具有相同数量的数据值。

这意味着,您可以从第一行计算点数,并假设它对其余行有效。

我不会为一次通话而汗流浃背。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    相关资源
    最近更新 更多