Search code examples
cstdin

Why does scanf pass the value to my function, dont want scanf to send value to callee


I am aware of scanf() usage and is not encouraged. But I've the problem, where scanf sends the stdin value to the next function stdin. I'm wondering why it's doing like this.

code:

#include <stdio.h>

void ffgets() {
    char name[40];
    printf("What's your name? ");
    if (fgets(name, 40, stdin)) {
        printf("Hello %s", name);
    }
}

int main(int argc, char **argv) {
    int a;
    printf("enter a number: ");

    int res = scanf("%d", &a);
    if (res > 0) {
        printf("Valid Integer %d.\n", a);
    } else {
        printf("It's not a number\n");
    }

    ffgets();
    return 0;
}

Output:

Test case 1:

Why the function doesn't ask for stdin, it just print empty string

 ./a.out 
enter a number: 23
Valid Integer 23.
What's your name? Hello 

Test case 2: I entered the string with the special character that is passed name.

./a.out 
enter a number: random##¤
It's not a number
What's your name? Hello random##¤

I dont want stdin value from main passed to the function, how to do that?


Solution

  • If you input something that scanf can not match to the format specification then it will stop immediately and leave the input in the input buffer for the next input function.

    Also, when using scanf it will not consume the trailing newline in the input buffer, also leaving it for the next input function.

    To solve both problems consider using fgets to get the whole line from the input, and then use sscanf to parse the string.