thechamp
some of my queries in C/C++
1) during input, user can enter endlessly until he presses ENTER KEY, i want to limit user's input character just like in GUIs. he can enter only 'x' characters for input.
2) simmilarly i want to limit the data type he wants to enter. for example if i am asking his age and he tries to enter characters instead of integers then character keys should not work. only numeric keys should work.
3) when i ask user to enter an integer, if he enters string or character my program clashes and end abruptly. how can i keep check on it, such that an error message is shown instead of program clashing.
please someone help
Solution for problem number 1:-
use the method fgets.
Syntax
char *fgets(char *str,int size,FILE *file)
Normally this function is used for reading from file but we can read from keyboard also using
stdin (refering it as a file)
Working
This method takes size-1 characters from the user and leaves 1 for null character.
No matter how long the user enters a string it will store only size-1 characters in your str character array.
This is a very good method to avoid buffer overflow.
Problem
If the user enters string of lesser size as you specified in the function then it also stores '\n' in your character array so you have to manually delete that.
Problem 2:-
I have not heard of this. So sorry in this case i may not help.
problem 3:-
You can always put a check on what user has entered.
You are expecting an integer and user has entered a string.
Simply always take input in the form of string and check if all characters lie between 48 and 57 (ASCII valued of 0 and 9)
And if it is true then convert your string in integer.
else print an error message.