-
Checking input
i am using this program to check input.
Where can i put error message in this program to show user if the input is not integer
cheers
Code:
char input[100];
int i;
do
{
printf("Give number: ");
scanf("%s", input);
for(i = 0; input[i] && isdigit(input[i]); i++) ;
} while(i != 6 || input[i]);
-
Code:
int isInteger( char [] );
int main()
{
char input[100];
printf("Give number: \n");
scanf("%s", input);
if(isInteger(input))
printf("\n Yes");
else
printf("\n No");
getch();
return 0;
}
int isInteger( char s[] ) {
int i, len = strlen(s);
if( len > 6) //...FIXME : not a "failsafe" validation scheme...
return 0;
for(i = 0; i < len; i++ )
{
if(!isdigit(s[i]))
return 0;
}
return 1;
}
-
Why not just check the return code from scanf() and use an int variable.
Code:
#include <stdio.h>
int main(void)
{
int i;
if (scanf("%d", &i) == 1)
printf("You entered a number %d\n", i);
else
printf("You did not enter a number\n");
return (0);
}
-
>Why not just check the return code from scanf() and use an int variable.
Two good reasons:
1) If the user enters a float value it will be truncated and all precision is lost when the program should flag an error for invalid input.
2) If this code is placed in a loop as is and invalid input is entered all hell will break loose.
With the problems in mind, and the work it would take to safely handle them, it's easier to transfer the number to an array and validate it that way.
-Prelude