[英]Scanf skipping character in c
int main(){
int firstNumber, secondNumber, thirdNumber;
char oper;
scanf("%d", &firstNumber);
printf("%d\n", firstNumber);
scanf("%c", &oper);
printf("%c\n", oper);
scanf("%d", &secondNumber);
printf("%d\n", secondNumber);
return 0;
}
Why this code doesn't work as expected, It reads the first and the second number but it doesn't read the character in between.为什么这段代码不能按预期工作,它读取第一个和第二个数字,但不读取它们之间的字符。
Using scanf()
is hard.使用scanf()
很难。 Here, there is a newline character left on stdin
from you hitting enter after the first number.在这里,在第一个数字后按回车键在stdin
留下了一个换行符。 So, that's the character you read.所以,这就是你读到的角色。 Some format conversions ignore whitespace, but %c
does not.某些格式转换会忽略空格,但%c
不会。
To make it ignore leading whitespace, you should instead use要使其忽略前导空格,您应该改用
scanf(" %c", &oper);
The space in the format string tells scanf()
to ignore any whitespaces it finds, so you will read a non-whitespace character.格式字符串中的空格告诉scanf()
忽略它找到的任何空格,因此您将读取一个非空格字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.