why is the desirable number not getting stored in C from the user input data

73 Views Asked by At

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??

2

There are 2 best solutions below

1
Oka On

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 %d specifier, so an input format such as 2t24 would work. You could instead match the : character explicitly, as in %d:%d.

As @Some programmer dude points out, the return value of scanf should always be checked to ensure you are not working with indeterminate values, in the event that a short number of conversions occurs.

#include <stdio.h>

int main(void)
{
    int hours, minutes;

    printf("What is the time: ");

    if (2 != scanf("%d:%d", &hours, &minutes)) {
        fputs("Invalid format.\n", stderr);
        return 1;
    }

    printf("%d\n%d\n", hours, minutes);
}
What is the time: 2:24
2
24
What is the time: 2t24
Invalid format.

You might also consider instead reading an entire line with fgets, and using sscanf or parsing a date and time format with a function like POSIX strptime.

0
arfneto On

scanf is, as we see in the name, a scanner and was written to consume large files of tabular data. You do not suppress the delimiter, you just inform the scanner what is such symbol. As in the example below, you can use "%2d:%2d" so scanf knows that the delimiter is : and 2 integer values of up to 2 digits each are expected.

RTFM: As pointed out in the comments by Some programmer dude, ALWAYS check the return value of the function. Since this is a scanner it can read from 0 to the total of items you asked for. And it will tell you how many in the returned value you did not test for. It can also return -1 for EOF or for some error...

Consider that, as scanners, to read nothing is not an error for these family of functions..

example

#include <stdio.h>
#include <string.h>
int main(void)
{
    int hh;
    int mm;
    const char* line = "2:4";
    int         res  = sscanf(line, "%2d:%2d", &hh, &mm);
    printf("    function read %d items, hour is %02d, minute is %02d\n", res, hh,mm);
    return 0;
}

// https://stackoverflow.com/questions/77907218/why-is-the-desirable-number-not-getting-stored-in-c-from-the-user-input-data

output

    function read 2 items, hour is 02, minute is 04