My goal is to use the property of scanf() function. I want to supress ':' in the input to get the hours and minutes value into their respective variables hours_var and minutes_var.
#include<stdio.h>
#include<string.h>
void main()
{
int hours_var,minutes_var;
printf("Whats the time??\n");
scanf("%d*c%d",&hours_var,&minutes_var);
printf("%d\n", hours_var);
printf("%d\n",minutes_var);
}
OUTPUT :
Whats the time??
2:24
2
0
I wanted 24 in the minutes_var variable . What did I miss??
As @mch explains, you are missing the format specifying character
%before*c. In full, the format string should be"%d%*c%d".Note that this will match (and discard) any character that is not consumed by the preceding
%dspecifier, so an input format such as2t24would work. You could instead match the:character explicitly, as in%d:%d.As @Some programmer dude points out, the return value of
scanfshould always be checked to ensure you are not working with indeterminate values, in the event that a short number of conversions occurs.You might also consider instead reading an entire line with
fgets, and usingsscanfor parsing a date and time format with a function like POSIXstrptime.