从文件中读取整数到数组

Read integers from a file into array

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

我有一个类似的文件:

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