Jon Martin
Jon Martin

Reputation: 3392

Reading integers from file in c++

I currently have a plain text file which contains three tables as follows:

0  0  0  0
20 20 0  0
100 150 150 150 
100 0 0 0
0 255 255 255


0 0 0 255
20 100 100 100
0 0 0 0
100 100 250 250
255 255 0  0


0 100 255 0
20 100 100 100
0 0 0 0
100 20 20 100
0 255 255 255

Each table represents RGB values for an image. The first table is all red, second table all green, third table all blue. I have int arrays red[][], green[][] and blue[][] that I want to store these values into.

I currently have a loop:

string data;
int count = 0;
while (getline(infile, data))
{
    // iterate though data line and store into array
    count++;
}

I definitely know that if count < 5 I should store into red array, < 11 into green array, etc, but I'm unsure how to get each individual number out for storage. What's the best way to do that?

Upvotes: 0

Views: 65

Answers (1)

user657267
user657267

Reputation: 20990

Use the data string to initialize an istringstream and extract the ints, for example:

while (getline(infile, data))
{
  std::istringstream iss(data);
  int i, j, k;
  iss >> i >> j >> k;
  count++;
}

Upvotes: 1

Related Questions