该程序扫描一些字符,并显示输入了多少个'x'
。
我认为您查看代码而不是我解释会得到更好的主意。
#include<stdio.h>
main()
{
int n,i,t=0;
scanf("%d",&n);
char ara[n];
for(i=0;i<n;i++)
{
scanf("%c", &ara[i]);
if(ara[i]=='x') t++;
}
printf("%d",t);
}
假设,n
= 5
并且字符是 "xxxxxx"
。在这种情况下,t
的值应该是 5
。但它显示 4
。
另一件事是,如果您删除第一个 scanf 语句(第 5 行)并在代码的其他任何地方手动设置 n
= 5
的值:
int n,i,t=0;
//scanf("%d",&n);
n = 5;
然后 t
的值变为 5
从而得到正确的输出。是否有可能是外部 scanf 函数影响了 for 循环内部的 scanf 函数?
最佳答案
这是因为当您输入 n
时,您还输入了换行符(或空格)。此空白字符留在缓冲区中,因此读入的第一个字符不是 x
,而是那个空白字符。
您可以通过告诉 scanf
跳过前导空格来解决这个问题。改变这一行
scanf("%c", &ara[i]);
对此:
scanf("%c", &ara[i]);
%c
前面的空格使其忽略换行符/空格,取而代之的是输入的第一个 x
,从而为您提供正确的结果。 reference 是这样的解释一下:
Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).
关于for循环内的计数器没有给出预期的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55607461/