1

Hi I will read from file and put the numbers which is seperated with white space int different array. Example file to read

15
10 2
20 1
30 1

This is what I did

    while(!file.eof()){ 
        file>>first[count++];

    }

By doing this I taking line by line but I want to read until white space and put the number after whitespace into different array. As a result array will look like this (assume first and second are dynamic integer arrays)

first={15,10,20,30}
second ={0,2,1,1}
mxyz
  • 63
  • 1
  • 2
  • 7
  • Note this Q&A: [Why is iostream::eof inside a loop condition considered wrong?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) You should fix this 1st. – πάντα ῥεῖ Nov 19 '14 at 14:14
  • no I just put 15 into one array and since there is no number after space I will put the 0 to second array. – mxyz Nov 19 '14 at 14:14
  • You can either run it once just to increment `count`, then allocate the array, rewind the file and run it again (this time saving the values into the array)... Or you can simply use a `vector`. – barak manos Nov 19 '14 at 14:20
  • @barakmanos thanks but using vector is not allowed – mxyz Nov 19 '14 at 14:22
  • Then use the first option – barak manos Nov 19 '14 at 14:24

1 Answers1

1

You should use string streams.

#include <sstream>
...

string line;
while(getline(file, line))
{
   istringstream iss(line);
   int firstNumOnLine, secondNumOnLine.
   iss >> firstNumOnLine;
   first.push_back(firstNumOnLine);
   if(iss >> secondNumOnLine)
   {
        //... 
        second.push_back(secondNumOnLine)
   }
   else
   {
       //... there was no second number on the line.
       second.push_back(0);
   }
}

Here, first and second are assumed to be vectors

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434