虽然遇到NULL字符后C中的循环不会中断

yas*_*shC 1 c while-loop

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

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

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

我试着用

while((ch=getchar())!='\0');
Run Code Online (Sandbox Code Playgroud)

但它给出了同样的问题.

das*_*ght 9

getchar不会'\0'在输入结束时返回:它不是从空终止的C字符串读取,而是从控制台,文件或其他流中读取.

如果没有其他输入,则getchar返回EOF.这是您应该检查以决定何时停止循环的条件.

Stack Overflow提供了很多关于如何实现循环读取的好例子getchar(链接#1 ; 链接#2 ;请注意示例中使用的数据类型).