C 中的 While 循环在遇到 NULL 字符后不会中断

While loop in C don't break even after encountering a NULL character

这里是添加字母数字字符串中存在的数字的代码:

#include<stdio.h>
#include<stdlib.h>
int main()
{
int total=0;
char ch;
printf("enter the string\n");
ch=getchar();
while(ch!='[=10=]')
{
    printf("I am here !!");
    if (!(isalpha(ch)))
        total+=(int)ch;
    ch=(char)getchar();
    printf("I am here !!");
}
printf("\ntotal is %d",total);
return 0;
}

无论我输入什么字符,它都会为每个字符提供 4 个“我在这里”。

我尝试使用

while((ch=getchar())!='[=11=]');

但它给出了同样的问题。

之所以不行是因为'[=11=]'不能从键盘输入,所以getchar()不太可能return'[=11=]',a测试输入结束的正确方法是

int ch;

while (((ch = getchar()) != EOF) && (ch != '\n'))

这是因为 EOF 意味着用户有意停止输入数据,而 '\n' 通常是 stdin 刷新时最后看到的内容,因为它会触发冲洗。

getchar 不在输入末尾 return '[=11=]':它是 not 从空终止的 C 字符串中读取, 但来自控制台、文件或其他流。

当没有可用的附加输入时,getchar returns EOF。这是您应该检查的条件,以决定何时停止循环。

Stack Overflow 提供了很多很好的例子来说明如何实现循环读取 getcharlink#1; link#2;请注意示例中使用的数据类型)。