0

I am frequently running into unexpected behavior while using the scanf() function in C. Especially with character variables.

For example:

int main()
{
    char c1, c2;
    int no;
    
    printf("Enter c1: ");
    scanf("%c", &c1);
    printf("\nEnter c2: ");
    scanf("%c", &c2); 
    printf("\nEnter age: ");
    scanf("%d", &no);
    
    printf("%c %d ", c1, no);
    printf("-%c-", c2);

    return 0;
}

Here, it seems, c2 is automatically taking 'new line' as the input.

I frequently run into errors of similar kinds with scanf(). Could someone explain what is happening here?

I don't know much C so please suggest good programming practices when using scanf() function to escape from such errors.

Since this is my first question on StackOverflow please forgive any inadvertent mistakes on my part :).

(I am not sure if this has already been answered before....)

Prad
  • 47
  • 8
  • 3
    My suggestion is: *Don't* use `scanf`. Instead use [`fgets`](https://en.cppreference.com/w/c/io/fgets) to read whole lines, and then use `sscanf` for the parsing. – Some programmer dude May 24 '22 at 08:45
  • `scanf` is a terrible function and it's even more terrible for reading characters with the `%c` conversion specifier because (as you could see) the `\n` itself is read by `scanf("%c",...)`. Do what the pervious comment suggests. It's impossible (or nearly impossible) to get interactive input right with `scanf`. – Jabberwocky May 24 '22 at 08:51
  • @Someprogrammerdude Thanks. Will do that from now. Found the solution to this also now :) – Prad May 24 '22 at 08:51
  • You might be interested in some of the other [secret rules for avoiding `scanf` gotchas](https://stackoverflow.com/questions/72178518/how-can-i-fix-the-scanf-to-take-data-into-the-array/72178652#72178652). (Your question was #11 on that list.) – Steve Summit May 24 '22 at 11:13
  • *Could someone explain what is happening here?* If you really want to know all the gory details, read [this long answer](https://stackoverflow.com/questions/68952584/how-does-scanf-know-if-it-should-scan-a-new-value/68952778#68952778). And when you get tired of `scanf`'s basket of deplorable traps, issues, and pitfalls, see [What can I use for input conversion instead of scanf?](https://stackoverflow.com/questions/58403537) – Steve Summit May 24 '22 at 11:17

0 Answers0