Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: scanf for char not working as expected [duplicate]

Tags:

c

char

scanf

I was recently running a c program in my PC. It have a for loop in which some char d is scanned. The for loop runs for 3 times. During each running it prints the the count of running and then scans the value of char d. The program is as follows

#include<stdio.h>

int main(){
    int f;
    char d;
    for(f=0;f<3;f++){
        printf("Choice %d\n", f);
        scanf("%c", &d);
    }
    return 0;
}

Now the trouble is that when I run the program, the for skips the scanf part when f is 1. Now if i changed the code as follows

#include<stdio.h>

int main(){
    int f;
    int d;
    for(f=0;f<3;f++){
        printf("Choice %d\n", f);
        scanf("%d", &d);
    }
    return 0;
}

Now the program works fine. and scanf is executed for every iteration of for loop.

What does seem to be the problem here? I mean when d is of type int it works fine, but when d is of type char it does not work correctly.

like image 207
Vivek Sasidharan Avatar asked Mar 18 '15 12:03

Vivek Sasidharan


People also ask

Why scanf is not working for char in c?

The problem is that when you enter a character for scanf("%c", &d); , you press the enter key. The character is consumed by the scanf and the newline character stays in the standard input stream( stdin ).

Why scanf function is not working?

This happens because every scanf() leaves a newline character in a buffer that is read by the next scanf. How to Solve the Above Problem? We can make scanf() to read a new line by using an extra \n, i.e., scanf(“%d\n”, &x) . In fact scanf(“%d “, &x) also works (Note the extra space).

Does scanf %s read newline?

%s tells scanf to discard any leading whitespace, including newlines. It will then read any non-whitespace characters, leaving any trailing whitespace in the input buffer.

What does %C do in c?

If you use %c , you'll print (or scan) a character, or char. If you use %d , you'll print (or scan) an integer. printf("%d", 0x70);


1 Answers

You have to change

scanf("%c", &d);

to

scanf(" %c", &d);
       ^
       |

Otherwise, scanf() will consider the previously entered ENTER key press.

Note:

  1. ENTER key press generates a \n, which is a vaild input for %c format specifier. Adding a space before %c tells scanf() to ignore all leading whitespace-like inputs (including that previously stored \n) and read the first non-whitespace character from stdin.

  2. As for the case with %d format specifier, it consumes (and ignores) any leading whitespace-like inputs before scanning for numeric inputs, so the second case does not suffer any issues.

like image 126
Sourav Ghosh Avatar answered Oct 01 '22 08:10

Sourav Ghosh