从文件中读取整数到数组
Read integers from a file into array
我有一个类似的文件:
1 20 42 45 ...(74 integers)
2 43 41 92 ...(74 integers)
有74行的74行被空间分开。
以下代码对我不起作用:
#define NUM 74
int info[NUM][NUM] = {0};
std::ifstream file("file.txt");
std::string line;
int i = 0, j;
while(std::getline(file, line)){
for(j=0; j<NUM; j++){
std::istringstream(line) >> info[i][j];
}
i++;
}
此代码仅将每一行的第一个值存储到Info [i]的74列中的每一行中。我知道我是否有每个行的列表,我可以使用: std :: istringstream(line)>>信息[i] [0]>> info [i] [1]但是我不确定如何为大量整数(例如74)做到这一点。
为内循环外部的每一行创建std::istringstream
,然后在内部循环中重复使用。
while(std::getline(file, line)){
std::istringstream line_stream(line);
for(j=0; j<NUM; j++){
line_stream >> info[i][j];
}
i++;
}
由于您已经知道自己读了整数,因此可以使用这样的格式输入:
std::ifstream in("text.txt");
int values[74][74];
for (int i = 0; i < 74; ++i)
for (int j = 0; j < 74; ++j)
in >> values[i][j];
我已经弄清楚了如何做。
需要像这样更改时循环:
while(std::getline(file,line)){
std::istringstream iss(line);
int val;
j = 0;
while(iss >> val){
info[i][j] = val;
j++;
}
i++;
}
相关文章:
- C++使用整数的压缩数组初始化对象
- 在一定长度后从数组中打印时缺少整数
- 是否基于数组B整数打印数组A中的整数
- 检查TCHAR数组输入是否为带符号整数C++
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 从二进制文件中读取整数数组
- 整数区间(或 int 数组)中每个数字的出现次数
- 新的整数数组向右移动?
- C++ 中的二维整数数组,每行中的元素数量不均匀
- 在数组中输入 n 个整数的列表,并以类似于钟摆来回移动的方式排列它们. 输入-1 3 2 5 4,输出5 3 1 2 4
- 给定一个整数数组,需要在Max_Heap上运行操作。得到错误"segmentation fault",有什么想法吗?(C++)
- 为什么在我的 main 函数中声明整数后我的整数数组中会出现错误?
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- 在 C++ 中将整数数组转换为位集表示形式的最佳方法?
- C++数组输入不接受一定数量的整数
- 从两个 4x64 位整数数组中获取取模
- 如何计算数组整数的总可能组合
- 2D 字符串数组 C++:整数串联成字符串
- 将数组整数2除以偶数和
- 将2d数组整数数据从c++发送到qml