Scanning a number having more data than predefined value

前端 未结 2 1180
执念已碎
执念已碎 2020-12-20 03:53
#include
main()
{

        unsigned int num;
        printf(\"enter the number:\\n\");
        scanf(\"%u\",&num);//4294967299 if i\'m scanning mo         


        
2条回答
  •  醉酒成梦
    2020-12-20 04:32

    From this scanf (and family) reference for the "%u" format:

    The format of the number is the same as expected by strtoul() with the value ​0​ for the base argument (base is determined by the first characters parsed)

    Then we go to the strtoul function, and read about the returned value:

    Integer value corresponding to the contents of str on success. If the converted value falls out of range of corresponding return type, range error occurs and ULONG_MAX or ULLONG_MAX is returned. If no conversion can be performed, ​0​ is returned.

    From this we can see that if you enter a too large value for the scanf "%u" format, then the result will be ULONG_MAX converted to unsigned int. However the result will differ on systems where sizeof(unsigned long) > sizeof(unsigned int). See below for information about that.


    It should be noted that on platforms with 64-bit unsigned long and 32-bit unsigned int, a value that is valid in the range of unsigned long will not be converted to e.g. UINT_MAX, instead it will be converted using modulo arithmetic as detailed here.

    Lets take the value like 4294967299. It is to big to fit in a 32-bit unsigned int, but fits very well in a 64-bit unsigned long. Therefore the call to strtoul will not return ULONG_MAX, but the value 4294967299. Using the standard conversion rules (linked to above), this will result in an unsigned int value of 3.

提交回复
热议问题