reading hex values from fstream into int

前端 未结 4 1371
南笙
南笙 2020-12-22 01:39

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

相关标签:
4条回答
  • 2020-12-22 02:14

    ... 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?

    0 讨论(0)
  • 2020-12-22 02:15

    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.

    0 讨论(0)
  • 2020-12-22 02:28

    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.

    0 讨论(0)
  • 2020-12-22 02:31

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

    0 讨论(0)
提交回复
热议问题