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!

3
  • 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. Commented Oct 12, 2013 at 0:42
  • intArray[inc] doesn't work because intArray has zero size. There are no valid indexes into it. You want intArray.push_back(result); Commented Oct 12, 2013 at 0:43
  • @igorTandetnik I initialized it and the same number appears. Not sure what is going on Commented Oct 12, 2013 at 1:15

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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
I think strtoll is fine, but I am not sure the base is 10 or 2?
hmm I might have misunderstood how to use the function I'll try base 2
ahh that was it! I thought you had to put the base to convert to. I was wrong thanks for all your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.