问题描述
#include <stdio.h>
int main(){
int a,b,c;
scanf("%d%d%d\n",&a,&b,&c);
printf("%d %d %d",a,b,c);
return 0;
}
看我要输入3个输入并打印3个输出...但是当我在scanf函数的末尾添加新行时,我必须给出4个输入才能得到3个输出(我得到前3个作为输入)... scanf在这里如何工作?在这种情况下:
Look I am taking 3 inputs and printing 3 outputs... But as I added a new line at the end of the scanf function I have to give 4 inputs to get 3 outputs(I get the first 3 I give as input)... How scanf works here?And in this case:
#include <stdio.h>
int main(){
double n[2][5]; int i,j;
for (i=0;i<=1;i++){
for(j=0;j<=4;j++){
scanf("%lf\n",&n[i][j]);
printf("Class=%d Roll=%d Marks=%lf\n",i+6,j+1,n[i][j]);
}
}
return 0;
}
看起来我必须给出11个输入才能获得10个输出...并且每当我输入一个输入时,我都会得到前一个输入作为输出... scanf在这里如何工作?
Look I have to give 11 inputs to get the 10 outputs... And each time I give a input I get the previous input as an output... How scanf is working here?
推荐答案
scanf格式的白色字符与输入中的白色字符序列匹配,直到非白色字符为止.
A white character in scanf format matches a sequence of white characters in the input until a non-white character.
换行符是一个白色字符,这说明了程序的行为.这意味着,如果您的scanf格式以换行符终止,则它不会结束,直到在最后一次解析的输入之后看到另一个非空白字符为止.
Newline is a white character and this explains the behavior of your program. Meaning that if your scanf format terminates by a newline, it does not finish until it sees an additional non-blank character after the last parsed input.
这篇关于如果我在末尾添加新行'\ n',scanf的工作原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!