【问题标题】:Reading integers from file in c++在 C++ 中从文件中读取整数
【发布时间】:2014-06-09 03:14:05
【问题描述】:

我目前有一个纯文本文件,其中包含如下三个表格:

0  0  0  0
20 20 0  0
100 150 150 150 
100 0 0 0
0 255 255 255


0 0 0 255
20 100 100 100
0 0 0 0
100 100 250 250
255 255 0  0


0 100 255 0
20 100 100 100
0 0 0 0
100 20 20 100
0 255 255 255

每个表代表图像的 RGB 值。第一张桌子全是红色的,第二张桌子全是绿色的,第三张桌子全是蓝色的。我有 int 数组 red[][]、green[][] 和 blue[][],我想将这些值存储到其中。

我目前有一个循环:

string data;
int count = 0;
while (getline(infile, data))
{
    // iterate though data line and store into array
    count++;
}

我绝对知道如果 count

【问题讨论】:

    标签: c++ file-io


    【解决方案1】:

    使用data字符串初始化istringstream并提取ints,例如:

    while (getline(infile, data))
    {
      std::istringstream iss(data);
      int i, j, k;
      iss >> i >> j >> k;
      count++;
    }
    

    【讨论】:

    • 如果该行是空的,这会起作用吗?有空行
    • @JonMartin 您必须以某种方式自己跟踪空行,您可能需要重新考虑您的文件格式。
    • 而不是count++;if ( iss ) { /* line had 3 numbers */ } else { /* line didn't have 3 numbers */ }
    • 如果您需要支持每行可变数量的数字,那么您需要将iss >> i >> j >> k 更改为while ( iss >> i ) { /* do something with i */ }
    • @MattMcNabb 确实有很多可以改进的地方。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-23
    • 1970-01-01
    相关资源
    最近更新 更多