正在用c++从文件中读取整数

Reading integers from file in c++

本文关键字:读取 整数 文件 c++      更新时间:2023-10-16

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

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++;
}

我肯定知道,如果计数<5我应该存储到红色数组中,<11放入绿色数组等,但我不确定如何将每个单独的数字取出存储。最好的方法是什么?

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

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