PDA

View Full Version : not getting any output from my program??




sg001
Aug 9, 2012, 07:21 AM
#include <stdio.h>

int main(int argc, char * argv[]){

#define SEC_PER_MIN 60
#define MIN_PER_HOUR 60
#define ERROR_MSG "Format must be HHMMSS"

int sec, min, hour;

printf("Enter 24 hour time in HHMMSS format:\n");
scanf("%d %d %d", &hour, &min, &sec);

if (hour>23 || min>59 || sec>59){
printf("No such time\n");
}
if (hour<0 || min<0 || sec<0){
printf("No such time");
}
else {
printf("The time is %d:%d:%d\n",hour, min, sec);
}
return 0;

For some reason when the program prompts me for "Enter...format"
and I enter any number i.e. 231314

I get no output?

and even a number like 251617 which is not in the format I should get an output "No such time!"

but if I enter characters i.e. ahdbsh, then I get "No such time"
which is what I want but I need it for numbers to.

Any thoughts on what mistakes I have made

Thanks.



robbieduncan
Aug 9, 2012, 07:40 AM
Does 231314 match the pattern "%d %d %d"? Or does it match "%d%d%d"?

sg001
Aug 10, 2012, 01:37 AM
Does 231314 match the pattern "%d %d %d"? Or does it match "%d%d%d"?

ok i fixed it now thanks

jaduff46
Aug 10, 2012, 08:35 AM
Another approach which I've used in the past is to use gets() to get a character string, then use sscanf (like scanf) on the string to get the data you want.

Benefits are that it will return the number of arguments converted (3 in your case, EOF on an error) and I find it easier to control (don't have to worry about flushing the stdin buffer on an error)

Admittedly haven't had to do this in awhile.

chown33
Aug 10, 2012, 11:17 AM
Another approach which I've used in the past is to use gets() to get a character string, ...

gets() is unsafe. It's vulnerable to uncontrollable buffer overruns.

Reading lines should use fgets(), never gets().

Cromulent
Aug 10, 2012, 03:54 PM
Another approach which I've used in the past is to use gets() to get a character string, then use sscanf (like scanf) on the string to get the data you want.

I'm surprised you didn't get a warning when using gets(). The Mac OS X implementation (and probably most others) prints a line to stdout when using the gets() function that explicitly states that you shouldn't use it.

In fact gets() is so bad it has been completely removed from the new C standard C11.