在双for循环中访问文件中的元素

Access an element within a file from within a double for loop?

本文关键字:元素 文件 访问 循环 在双 for      更新时间:2023-10-16

我有一个带有数字网格的文件,我正在尝试迭代。我知道网格的尺寸,但我似乎找不到一种方法来访问每个位置的值。下面是目前为止我得到的部分伪代码的概要:

std::ifstream file(filename);
for (y = 0; y < height; y++)
{
    string line = file[y];  // wrong
    for (x = 0; x < width; x++)
    {
        int value = line[x]  // wrong
    }
}

实现这一点的最好方法是什么?谢谢你的帮助。

看起来应该是这样的:

for (int y = 0; y < height; y++)
{
    string line;
    getline(file,line);
    std::istringstream line_stream(line);
    for (int x = 0; x < width; x++)
    {
        int value;
        line_stream >> value;
    }
}

您不能访问这样的流,它本质上是串行的。使用流的伪代码可能看起来像这样(没有尝试编译,但这就是想法)

#include <iostream>     // std::cout
#include <fstream>      // std::ifstream
int main () {
  std::ifstream ifs ("test.txt", std::ifstream::in);
#define LINE_SIZE 10    
  char c = ifs.get();
  for (int i=0;ifs.good();i++) {
      // this element is  at row :(i/LINE_SIZE)  col: i%LINE_SIZE
      int row=(int)(i/LINE_SIZE);
      int col=(i%LINE_SIZE);
    myFunction(row,col,c);
    c = ifs.get();
  }
  ifs.close();
  return 0;
}