1
#include "stdafx.h"
#include <stdlib.h>

void main()
{
    char buffer[20];
    int num;

    printf("Please enter a number\n");
    fgets(buffer, 20, stdin);
    num = atoi(buffer);

    if(num == '\0')
    {
        printf("Error Message!");
    }

    else
    {
        printf("\n\nThe number entered is %d", num);
    }

    getchar();
}

The above code accepts a number in the form of a string and converts it to integer using atoi. If the user inputs a decimal number, only the bit before the decimal is accepted. Moreover, if the user enters a letter, it returns 0.

Now, I have two queries:

i) I want the program to detect if the user entered a number with decimal point and output an error message. I don't want it to take the part before the decimal point. I want it to recognize that the input is invalid.

ii) If atoi returns 0 in case there are letters, how can I validate it since the user can enter the number 0 as well?

Thanks.

alk
  • 69,737
  • 10
  • 105
  • 255
Matthew
  • 4,477
  • 21
  • 70
  • 93
  • 1
    Maybe duplicate of http://stackoverflow.com/questions/8871711/atoi-how-to-identify-the-diffrence-between-zero-and-error – Xymostech Mar 05 '13 at 16:45
  • What do you want? To make sure the user inputs an whole number or to know if the user inputs a floating number? -- Check ctype.h. It has some functions isnumber(), isdigit() and so on. – Abu Dun Mar 05 '13 at 16:50
  • 4
    `printf( "Error message" )` is *always* wrong. You meant `fprintf( stderr, "Error message" )`. Errors belong on `stderr`. `stdout` is for output. – William Pursell Mar 05 '13 at 16:51
  • 1
    And again, the return type of `main` is `int`, not `void`. – Fred Foo Mar 05 '13 at 16:51
  • @Sascha Yes, I want to know if the user inputs a whole number – Matthew Mar 05 '13 at 16:55
  • @larsmans Oops. I forgot to correct it. Thanks :) – Matthew Mar 05 '13 at 16:56

2 Answers2

7

atoi is not suitable for error checking. Use strtol or strtoul instead.

#include <errno.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>

long int result;
char *pend;

errno = 0;
result = strtol (buffer, &pend, 10);

if (result == LONG_MIN && errno != 0) 
{
  /* Underflow. */
}

if (result == LONG_MAX && errno != 0) 
{
  /* Overflow. */
}

if (*pend != '\0') 
{
    /* Integer followed by some stuff (floating-point number for instance). */
}
md5
  • 23,373
  • 3
  • 44
  • 93
0

There is the isdigit function that can help you check each character:

#include <ctype.h>

/* ... */

for (i=0; buffer[i]; i++) {
        if (!isdigit(buffer[i])) {
            printf("Bad\n");
            break;
        }
}   
perreal
  • 94,503
  • 21
  • 155
  • 181