将整数从文件读入数组 [英] Read integers from a file into array

查看:140
本文介绍了将整数从文件读入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的文件:

1 20 42 45 ...(74 integers)
2 43 41 92 ...(74 integers)

74行74个整数, 。

There are 74 rows of 74 integers each separated by spaces.

以下代码不适用于我:

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

此代码仅将每行的第一个值存储到74列的信息[i]。
我知道如果我有一个每行说2个整数的列表,我可以使用:
std :: istringstream(line)>> info [i] [0] >> info [i] [1] ]
但是我不知道如何对大数的整数(如74)做这个。

This code stores only the first value of each row into each of the 74 columns of info[i]. I know if I had a list of say 2 integers per row, i could use: std::istringstream(line) >> info[i][0] >> info[i][1] But I am not sure how to do this for high number of integers (like 74).

推荐答案

std :: istringstream 对于内循环之外的每一行,并在内循环内重用。

Create the std::istringstream for each line outside the inner loop and re-use it inside the inner loop.

while(std::getline(file, line)){
    std::istringstream line_stream(line);
    for(j=0; j<NUM; j++){
         line_stream >> info[i][j];
    }
    i++;
}

这篇关于将整数从文件读入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆