AMM
AMM

Reputation: 17920

reading hex values from fstream into int

I have a text file which has one hex value in each line. Something like

80000000
08000000
0a000000

Now i am writing a c++ code to read this directly. SOmething like

fstream f(filename, ios::in);

while(!f.eof)
{
    int x;
    char ch;
    f>>std::hex>>x>>ch;  // The intention of having ch is to read the '\n'
}

Now this is not working as expected. While some of the numbers are getting populated properly, the ch logic is flawed. Can anybody tell me the right way of doing it. I basicaly need to populate an array with the int equivalent.

Upvotes: 1

Views: 4196

Answers (4)

Loki Astari
Loki Astari

Reputation: 264381

This works:

#include <iostream>
#include <fstream>

int main()
{
    std::ifstream f("AAPlop");

    unsigned int a;
    while(f >> std::hex >> a)   /// Notice how the loop is done.
    {
        std::cout << "I("<<a<<")\n";
    }
}

Note: I had to change the type of a to unsigned int because it was overflowing an int and thus causing the loop to fail.

80000000:

As a hex value this sets the top bit of a 32 bit value. Which on my system overflows an int (sizeof(int) == 4 on my system). This sets the stream into a bad state and no further reading works. In the OP loop this will result in an infinite loop as EOF is never set; in the loop above it will never enter the main body and the code will exit.

Upvotes: 5

ildjarn
ildjarn

Reputation: 62975

As mentioned, extracting whitespace manually in the code you've shown is unnecessary. However, if you do come across a need for this in the future, you can do so with the std::ws manipulator.

Upvotes: 0

davka
davka

Reputation: 14682

... and the way to change it is to use noskipws: f >> std::noskipws; will set no skipping of whitespace until you use std::skipws manipulator.

But why do you want to read the '\n'? To make sure that there is one number per line? Is it necessary?

Upvotes: 0

octal9
octal9

Reputation: 368

fstream::operator>> will ignore whitespace so you don't have to concern yourself with eating the newline.

Upvotes: 1

Related Questions