0

I have to read from a text file that contains a bunch of binary numbers and then convert them to integers and store these in an array. I have made a function to do this, however, the function is only returning one number. It seems to not be going through the file, or it just doesn't work. Can anyone figure out why?

void readf4()
{
    std::ifstream inFile("f4.txt");
    std::vector<int> intArray;
    std::string line;
    //unsigned num = 0;
    int inc = 0;
    char * pEnd;
    for(unsigned long int result; std::getline(inFile,line); result = strtol(line.c_str(),&pEnd,10))
    {
        //seg fault if I include these lines
        //intArray[inc] = result;
        //inc++;

        cout<<result;//always returns 9223372036854775807
        cout<<"\n";
    }
}

Thanks in advance!

Andy
  • 281
  • 2
  • 7
  • 23
  • On the first iteration of the loop, `result` is uninitialized. The increment expression in the `for` loop is executed between iterations, but not before the first iteration. – Igor Tandetnik Oct 12 '13 at 00:42
  • `intArray[inc]` doesn't work because `intArray` has zero size. There are no valid indexes into it. You want `intArray.push_back(result);` – Igor Tandetnik Oct 12 '13 at 00:43
  • @igorTandetnik I initialized it and the same number appears. Not sure what is going on – Andy Oct 12 '13 at 01:15

1 Answers1

1

The problem you have is that you use an empty vector and try to assign something to its element.

You need to use

intArray.push_back(result);

And you need to initialize result first.

CS Pei
  • 10,869
  • 1
  • 27
  • 46
  • so I change my for to `for(unsigned long int result = 0;....` and is `strtol` the correct function for changing from a binary string to an integer? Thanks for the help – Andy Oct 12 '13 at 00:56
  • I think `strtoll` is fine, but I am not sure the `base` is 10 or 2? – CS Pei Oct 12 '13 at 01:14
  • hmm I might have misunderstood how to use the function I'll try base 2 – Andy Oct 12 '13 at 01:17
  • ahh that was it! I thought you had to put the base to convert to. I was wrong thanks for all your help! – Andy Oct 12 '13 at 01:18