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!


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;

        if(ch>='0'&& ch<='9')
            //Code here
            str[i++] = ch;

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


    }while(i<9 && ch!='\r');
    str[i] = '\0';
    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! :)

This article has been dead for over six months. Start a new discussion instead.