我有一个文本文件,其中包含 1000 行,每行 130 个数字。 我想将数字导入一个数组,然后使用它们。 我想打印出每行的前两个数字,我使用了一个循环,但它没有按预期工作。 输出应该是这样的
1 126
2 124
3 128
4 123
// etc...
代码是:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include<cstdlib>
#include <array>
int main()
{
int l=0, r=0;
int line[1000][1000];
std::ifstream in("bragg_events.txt");
if (!in) {
std::cout << "Cannot open file.\n";
return;
}
for (l = 0; l < 1000; l++)
{
for (r = 0; r < 130; r++)
{
in >> line[r][l];
}
std::cout << line[0][l] << " " << line[1][l] << "\n";
}
in.close();
return 0;
}
它实际上打印:
1 126(正常)
20 34(不正常)
64 61
38 54
113 130
152164
你猜出哪里出了问题吗?
最佳答案
您的std::cout
语句必须在for
循环之外。 Line[1][l]
未在 r
的第一个循环中初始化。正确的?
关于c++ - 从文本文件中选取数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34480068/