Reading hexadecimal values โ€‹โ€‹from fstream to int

I have a text file with a hex value in each line. Sort of

80000000 08000000 0a000000 

Now I am writing 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 does not work as expected. Although some digits are filled in properly, the ch logic is wrong. Can someone tell me the correct way to do this. I need to fill the array with an int equivalent.

+1
source share
4 answers

It 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 type a to unsigned int because it overflowed int and thus caused a loop to fail.

 80000000: 

As the hexadecimal value, the upper bit of the 32-bit value is set. Which on my system overflows int (sizeof (int) == 4 on my system). This sets the thread to a bad state and no further reading is performed. In an OP loop, this will lead to an endless loop since EOF will never be set; in the loop above, it will never enter the main body and the code will not exit.

+5
source

fstream :: operator โ†’ will ignore spaces, so you donโ€™t have to worry about eating a new line.

+1
source

... and the way to change it is to use noskipws : f >> std::noskipws; will not skip spaces until you use the std::skipws .

But why do you want to read '\n' ? To make sure there is one number per line? It's necessary?

0
source

As already mentioned, manually extracting spaces in the code you specified is not required. However, if you are faced with the need for this in the future, you can do this using the std::ws manipulator.

0
source

All Articles