在双for循环中访问文件中的元素
Access an element within a file from within a double for loop?
我有一个带有数字网格的文件,我正在尝试迭代。我知道网格的尺寸,但我似乎找不到一种方法来访问每个位置的值。下面是目前为止我得到的部分伪代码的概要:
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;
}
相关文章:
- 如何在C++中确定文本文件中的元素是字符还是数字
- 比较文本文件的元素
- 使用 libxml2 解析 XML 文件时缺少元素值
- 比较文本文件的元素
- 从二进制文件中读取元素时引发异常(引发异常:读取访问冲突. _Pnext 0xB414D4)
- 如何在C++中将.csv文件的元素存储到二维向量中?
- 如何在 C++ 中将从文本文件中读取的元素推送和弹出到数组中,并按 Revserse 顺序输出堆栈?
- OpenCV 文件存储 - 错误:元素之间的解析错误 (icvYMLParseValue) 缺失
- 尝试读取数据文件,存储在数组中并打印所有元素,但它不起作用
- 计算TXT文件中元素的数量
- 使用提升属性树检查 xml 文件中是否存在元素
- 如何在头文件中定义结构的元素
- 可视化地将数组的所有元素输出到 C++ 中的文件中
- 在 c++ 中替换文件中特定位置的元素
- 将多种数据类型写入文件时的其他行和额外的数组元素
- 将数据从文件读取到链接列表中,并在链接列表中搜索元素
- 从字符串转换为float时,丢失文件中的第一行元素
- C++2d数组,用文件中最后一个元素值填充所有元素
- 使用 CDT 从头文件中获取属性定义的节点元素是什么
- 如何将文件的元素放入列表中