无法理解在scanf中的空白处理() [英] Can't understand whitespace handling in scanf()
问题描述
根据 HTTP pference.com/w/cpp/io/c/fscanf 的格式字符串中的任何一个空格字符使用所有可用的连续的空格字符从输入
因此,在下面的code:
#包括LT&;&stdio.h中GT;长FAC(INT N)
{
如果(N == 1)返回1;
否则返回(N * FAC(N-1));
}诠释的main()
{
INT T,N;
scanf函数(%d个,& T公司);
而(T--)
{
scanf函数(%d个,&安培; N);
的printf(%d个的阶乘是%ld个\\ N,N,FAC(N));
}
返回0;
}
如果\\ n保留在输入缓冲区,然后不应该scanf()的\\ n的ASCII code中的值保存到变量n在该语句scanf函数(%d个,&安培; N);遇到的第一次。
在格式字符串中的任何单个空格字符使用所有可用的连续的空格字符从输入
块引用>这是
%C
说明真实的。字符CH;
INT N;
scanf函数(%d个,&安培; N);
scanf函数(%C,&安培; CH);第二
scanf函数
不会跳过\\ n
首先留下scanf函数
。但scanf函数(%C,&安培; CH);
将跳过。
如果\\ n保留在输入缓冲区,然后不应该scanf()的\\ n的ASCII code中的值保存到变量n在该语句scanf函数(%d个,&安培; N);遇到首次。
块引用>在C,
%d个
忽略前导空格字符。它会跳过\\ n
。According to http://en.cppreference.com/w/cpp/io/c/fscanf any single whitespace character in the format string consumes all available consecutive whitespace characters from the input
So in the following code:
#include<stdio.h> long fac(int n) { if(n==1) return 1; else return (n*fac(n-1)); } int main() { int t,n; scanf("%d",&t); while(t--) { scanf("%d",&n); printf("Factorial of %d is %ld\n",n,fac(n)); } return 0; }
if \n remains in the input buffer then shouldnt scanf() save the value of \n in ASCII code to the variable n when the statement scanf("%d",&n); is encountered for the first time.
解决方案any single whitespace character in the format string consumes all available consecutive whitespace characters from the input
This is true for
%c
specifier.char ch; int n; scanf("%d", &n); scanf("%c", &ch);
the second
scanf
doesn't skip\n
left behind by firstscanf
. Butscanf(" %c", &ch);
will skip.
if \n remains in the input buffer then shouldnt scanf() save the value of \n in ASCII code to the variable n when the statement scanf("%d",&n); is encountered for the first time.
In C,
%d
ignores the leading white space characters. It will skip\n
.这篇关于无法理解在scanf中的空白处理()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!