Search code examples
cinputintegerdoublescanf

return error if scanf of a integer get a float or double


I made a program in it that uses a scanf to receive values ​​and put them in an array. the problem: if I enter a double instead of an int, the program continues and converts the double to an int. I want to do this scanf but if I receive 1.2 for example I return error of input and return 0;

if (!scanf("%d",&lst[i]) or (int)lst[i]==lst[i]){
         printf("error of input");
         return 0;}

dont work


Solution

  • You can use scanf with %s format (or use another function) to write the characters that the user printed to a char buffer (e.g. char buffer[256]), and then you can turn it to an int using the atoi function.

    Since you also want to check if the input contain anything else after the int, you can use strtol instead of atoi, since atoi is equivalent to strtol(nptr, NULL, 10); (according to the manual page). But, strtol has the advantage that it returns (via the endptr out-param) a pointer to the character that is after the last character that was parsed to int. In your case, I assume you expect this character to be '\n', so you can simply check that, and if it is not '\n' then you can print an error.