PDA

View Full Version : how to print error msg for non numeric input




sg001
Aug 10, 2012, 01:47 AM
How would I go about printing an error msg for non numeric inputs...

my code basically has input the time in HHMMSS

but if a user enters aabbcc i would like to print error msg

I tried this but it didn't work

if (time!=int){
printf("Format must be HHMMSS\n");
return 0;
}
??



sg001
Aug 10, 2012, 02:42 AM
How would I go about printing an error msg for non numeric inputs...

my code basically has input the time in HHMMSS

but if a user enters aabbcc i would like to print error msg

I tried this but it didn't work

if (time!=int){
printf("Format must be HHMMSS\n");
return 0;
}
??

ok I figured it out by doing

if(scanf("%d", &time) !=1){
printf("Format must be HHMMSS\n");
return 0;

but now it does not have an output when I do enter numbers for some reason?

i.e. if I enter 123543 it reads "Format must be in HHMMSS"


any suggestions on how to fix this?

pilotError
Aug 12, 2012, 08:20 AM
ok I figured it out by doing

if(scanf("%d", &time) !=1){
printf("Format must be HHMMSS\n");
return 0;

but now it does not have an output when I do enter numbers for some reason?

i.e. if I enter 123543 it reads "Format must be in HHMMSS"


any suggestions on how to fix this?

A couple of ways you can do it.

You can read it as a string and write a little function to parse/validate the string.

if (strlen(timestr) != 6)
printf("Invalid Time Entered");

Then break up the string into the individual components.

First two digits are the hour - copy the first two digits into another string and convert it to an integer (atoi)
if (hours < 0) || (hours > 24)
printf("Invalid Time, Hours needs to be 0 - 24");

Well you get the idea for the rest...