for循环内的计数器没有给出预期的输出
Counter inside a for loop does not give expected output
此程序扫描一些字符,并显示有多少 '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
时,您还输入了换行符(或 space)。这个 whitespace 留在缓冲区中,所以第一个读入的字符不会是 x
,而是那个 whitespace 字符。
您可以通过告诉 scanf
跳过前导白色 space 来解决这个问题。更改此行
scanf("%c", &ara[i]);
为此:
scanf(" %c", &ara[i]);
%c
前面的 space 使其忽略 newline/space 而是取第一个输入的 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).
您的 ara 数组在您输入 5
后立即包含换行符。要丢弃此换行符(以及第一个 'x' 之前的所有换行符和 spaces),您应该将 space 放在 %d
之后:
scanf("%d ",&n);
编辑
您可以像@Blaze 的回答中那样在“%c”之前添加一个space,但是像下面这样的输入会被误读:
5
x x x x x
它将被读作 'x', 'x', 'x', 'x', 'x'
而不是 'x', ' ', 'x', ' ', 'x'
。
附录:
如果您只想丢弃一个换行符,而不是所有换行符:
scanf("%d",&n);
while (true) {
char ch = getchar();
if (ch == EOF || ch == '\n') break;
}
此程序扫描一些字符,并显示有多少 '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
时,您还输入了换行符(或 space)。这个 whitespace 留在缓冲区中,所以第一个读入的字符不会是 x
,而是那个 whitespace 字符。
您可以通过告诉 scanf
跳过前导白色 space 来解决这个问题。更改此行
scanf("%c", &ara[i]);
为此:
scanf(" %c", &ara[i]);
%c
前面的 space 使其忽略 newline/space 而是取第一个输入的 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).
您的 ara 数组在您输入 5
后立即包含换行符。要丢弃此换行符(以及第一个 'x' 之前的所有换行符和 spaces),您应该将 space 放在 %d
之后:
scanf("%d ",&n);
编辑
您可以像@Blaze 的回答中那样在“%c”之前添加一个space,但是像下面这样的输入会被误读:
5
x x x x x
它将被读作 'x', 'x', 'x', 'x', 'x'
而不是 'x', ' ', 'x', ' ', 'x'
。
附录:
如果您只想丢弃一个换行符,而不是所有换行符:
scanf("%d",&n);
while (true) {
char ch = getchar();
if (ch == EOF || ch == '\n') break;
}