c - 在 C 中 - 循环内递增的变量不保留值 CS50

标签 c cs50

我是 C 新手,有以下代码:

#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>


int main(int argc, string argv[])
{
    string s = get_string("Enter string: ");
    int measure = 0;
    for(int i = 0; i < strlen(s);i++)
    {
        if(isalpha(s[i])==0)
        {
            measure++;
        }

    }
    printf("Measure is now %i\n", measure);
}

如果我将 printf 放在循环中,我可以正确地看到测量递增,但是当循环完成后我有 printf 时,它会返回到零。我相信这是一个范围问题,但我的理解是,在循环外部声明的变量(在本例中为度量)具有主函数的范围,因此可以在 for 和 while 循环中进行修改。我认为这是错误的,我不确定如何在循环范围内获取传递回主函数的值。

编辑:我将按原样保留这篇文章,以便下面的评论有意义。 @MaroBonelli 让我注意到我在两个窗口之间感到困惑,并且此代码中循环内的 printf 实际上并未打印值。

最佳答案

将我的评论转化为答案:

如果您不以某种方式明确重置该值,则该值不会重置为 0。如果您打算计算字母字符,那么此检查是错误的:

if (isalpha(s[i]) == 0) 

应该是完全相反的:

if (isalpha(s[i]))
// or
if (isalpha(s[i]) != 0)

来自 isalpha 的手册页:

RETURN VALUE

The values returned are nonzero if the character c falls into the tested class, and zero if not.

关于c - 在 C 中 - 循环内递增的变量不保留值 CS50,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57129531/

相关文章:

c - MPI 矩阵 vector 乘法返回有时正确有时奇怪的值

c - 为什么我的程序不能使用 float 变量,但可以使用 int 变量?

c - 从用户/新开发人员的角度来看,如何防止未定义的行为?

创建一个函数; scanf 和 char 问题

c - gcc编译器错误: "cannot find -lcs50 collect2: Id returned 1 exit status"

c - atomic_exchange_explicit/atomic_exchange 引入的内存顺序

c - 为什么我的密文得到负值?

C - 为什么删除未使用的变量声明时我的代码会中断

CS50 恢复段错误问题

经典 C. 在 execvp 函数、stdin 和 stdout 重定向中使用管道