关于#c语言#的问题:为什么输入#还是没有结束输入

题目内容:
从键盘读取用户输入直到遇到#字符,编写程序统计读取的空格数目、读取的换行符数目以及读取的所有其他字符数目。(要求用getchar()输入字符)

#include 
int main()
{
   char ch;
   int cnt=0,cnt1=0,cnt2=0;
   while((scanf("%c",&ch))!='#')
   {
       if(ch==' ')
       cnt++;
       else if(ch=='\n')
       cnt1++;
       else
       cnt2++;
   }
   printf("%d %d %d",cnt,cnt1,cnt2);
   return 0;
}

为什么输入#还是没有结束输入?

因为scanf()函数的返回值是成功从输入读取的数据项数,在这个例子,如果成功读取一个字符则返回1,否则返回0,所以用这个返回值!='#' 会一直不成立,因为'#'对应的ASCII 码值是35, 比较的实际是它的ASCII码值,1或0肯定是都不会等于35的;

如果需要使用getchar()(注释贴出了使用scanf()函数的修改办法),可修改如下:

参考链接:


http://ascii.wjccx.com/

#include <stdio.h>
int main()
{
   char ch;
   int cnt=0,cnt1=0,cnt2=0;
   // http://ascii.wjccx.com/
   // https://baike.baidu.com/item/scanf/10773316?fr=aladdin
   
 // while((scanf("%c",&ch))==1&&ch!='#')  // 如果使用scanf()可这样修改 
   while((ch=getchar())!='#')  //使用getchar() 
   {
       if(ch==' ')
       cnt++;
       else if(ch=='\n')
       cnt1++;
       else
       cnt2++;
   }
   printf("%d %d %d",cnt,cnt1,cnt2);
   return 0;
}

img