Hello.,
I haveto check for non-numerci input, when reading numeric input. I know how to validate numeric input with while loop, but what if i need numeric input and user inputs alphabetic letter, any suggestions??
Thanx a lot!

cheers!

Dani AI

Generated

Atman asked how to detect non-numeric input when numeric input is required. was right to steer away from scanf; ’s getch-based demo shows per-character checking but is nonportable and a bit fragile. A safer, portable pattern is: read one line into a bounded buffer, then parse and validate that the entire line is a valid number (and that the value fits the target type).

A concise checklist:

  • Read a full line with fgets into a fixed-size buffer.
  • Use strtol (integers) or strtod (floats) with an endptr to parse.
  • Ensure endptr advanced past digits and that any remaining characters are only whitespace.
  • Check errno == ERANGE and range limits to catch overflow/underflow.
  • Reject empty input or lines that contain non-numeric characters after parsing.

A simple pattern follows (read, parse, validate, repeat):

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

/* Example: read a base-10 int into *out; returns 0 on success, -1 on EOF */
int read_int(int *out) {
    char buf[128];
    char *end;
    long v;

    if (!fgets(buf, sizeof buf, stdin)) return -1;
    buf[strcspn(buf, "\n")] = '\0';
    errno = 0;
    v = strtol(buf, &end, 10);
    if (end == buf) return 1; /* no digits */
    while (isspace((unsigned char)*end)) end++;
    if (*end != '\0') return 2; /* junk after number */
    if (errno == ERANGE || v < INT_MIN || v > INT_MAX) return 3; /* out of range */
    *out = (int)v;
    return 0;
}

Notes: use base 10 unless other bases are desired; use strtoll for larger integers; always size the buffer and handle EOF. See fgets and strtol for details: fgets reference and strtol reference.

Recommended Answers

All 2 Replies

First you need to use a function for reading input, that will not stab you on the back as scanf() does. ;)
Take a look at fgets() and how it works. With it you can always limit the amount of input it will read from stdin, and you'll be always sure that the data is a string. Which can be compared and parsed and validated it in whatsoever form you devise.

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define MAX 10

int main()
{
    char ch, str[MAX];
    int i=0;
    do
    {
        ch=getch();

        if(ch>='0'&& ch<='9')
        {
            //Code here
            printf("%c",ch);
            str[i++] = ch;
        }

        else if(ch!='\r')
        {
            printf("\nDo not enter alphabet. It'll be ignored\n");
            printf("Enter the no again\n");
            for(i=0;i<MAX;i++)
                str[i] = '\0';
            i=0;

        }

    }while(i<9 && ch!='\r');
    str[i] = '\0';
    printf("\n%s\n",str);
    return 0;
}

This piece of code will check the user input after every character and validates it. Admittedly, it's a li'l crappy since it uses non-portable 'getch()' and i'm not even sure if Enter key returns '\r' on all machines(it does in mine), which will make you wonder why i'm posting it in the first place :P (Actually it's cause i was trying to make the input interactive and this is the closest i've got. Maybe there are better ways.) Anyway, validating after the user has given the input using fgets seems much safer and simpler. In case you like to use the code above, go nuts! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.