user1220086
user1220086

Reputation: 215

Read integers from a file into array

I have a file like so:

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

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

The following code is not working for me:

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

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).

Upvotes: 1

Views: 1550

Answers (3)

Baum mit Augen
Baum mit Augen

Reputation: 50111

Since you already know you read integers, you can use formatted input like this:

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];

Upvotes: 2

user1220086
user1220086

Reputation: 215

I've figured out how to do it.

need alter the while loop like so:

while(std::getline(file,line)){
    std::istringstream iss(line);
    int val;
    j = 0;
    while(iss >> val){
        info[i][j] = val;
        j++;
    }
    i++;
}

Upvotes: 1

user3146587
user3146587

Reputation: 4320

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

Upvotes: 4

Related Questions