Search code examples
c++scanfunsigned

Filtering out negative numbers using scanf


my aim is to scan for some positive-only a, if negative number is entered, the function should print error:

if ( scanf("%u %lf", &a, &b) != 2 ) {
    //error
}

Now the theory is that scanf returns successful writing attempts, so if I enter a negative number, scanf shouldn't return 2. My theory seems to be incorrect, why?

Obviously I could simply scanf %d and then check whether %d is negative but right now I'm curious why my initial theory is incorrect. So is there a way without scanning and then comparing?


Solution

  • Your theory doesn't work because scanf doesn't fail or doesn't refuse to copy the user input to the memory address specified even if a signed number is entered when an unsigned number is expected. Therefore, as per the scanf documentation, scanf will return the number of items copied to the provided memory address.