Beginner from C: disappointment in a simple program

#include<stdio.h> int main() { char a, b; scanf("%c", &a); scanf("%c", &b); printf("%c %c",a,b); return 0; } 

When I run this program, I get only output in the form of a, and I do not receive an invitation to enter the 2nd character. Why?

+4
source share
3 answers

In this line

 scanf("%c", &a); 

you are actually accepting% d from stdin (standard input), but while you typed a character from stdin, you also typed ENTER from the keyboard, which means that now you have two characters in stdin; the character itself and \ n. So, the program accepted the first character as the one you entered and the second character as \n .

You need to use

 scanf("%c\n", &a); 

to scan a new line (also by pressing the ENTER key).

Like rodrigo , you can also use them.

 scanf(" %c", &a); or scanf("%c ", &a); 

The way you think the second character is printed is wrong. It does print, but it's \ n, so your prompt may go to the next line.

Your code will work if you enter both characters without using ENTER.

 shadyabhi@archlinux /tmp $ ./a.out qw q wshadyabhi@archlinux /tmp $ 

Note. When you used this, the only things that were in STDIN were q and w. So, the first is scanf ate q , and the second is w .

+11
source

Because when you press enter , the resulting newline is read as a single character in b . Try instead:

 #include<stdio.h> int main() { char a, b; scanf("%c %c", &a, &b); printf("%c %c",a,b); return 0; } 
+2
source

% c is a format string that accepts only one character. I think you hit Enter as soon as you hit the alphabet key. The Enter key is also recognized as a character. So, the next variable takes an input key that has a value of "\ 0".
The computer still prints a character from the second variable, but its invisible because nothing is printed. If you watch closely, a new line will appear.
Enter two characters one by one and you will get the correct output.

0
source

Source: https://habr.com/ru/post/1393426/


All Articles