reading hex values from fstream into int

前端 未结 4 1390
南笙
南笙 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:28

    This works:

    #include 
    #include 
    
    int main()
    {
        std::ifstream f("AAPlop");
    
        unsigned int a;
        while(f >> std::hex >> a)   /// Notice how the loop is done.
        {
            std::cout << "I("<

    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.

提交回复
热议问题