for循环内的计数器没有给出预期的输出

标签 c for-loop variable-assignment

该程序扫描一些字符,并显示输入了多少个'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/

相关文章:

c - 为什么 valgrind 提示单个链表节点删除时大小为 8 的无效读取?

arrays - 如果数组末尾的额外元素在嵌套循环的下一次迭代中更短,如何计算数组末尾的额外元素

python - 将文件写入元组列表

PHP:仅执行for循环来显示html

c - 什么时候应该使用指针分配给 int?

C在while循环中读取输入

c - For 循环卡在 C (cygwin) 中的函数调用中,非常奇怪的行为我无法理解

c++ - 位移位和赋值

python - 我可以在Python中的for循环内更改for循环外的变量吗?

java - %= 在 Java 中是什么意思?