鱼C论坛

 找回密码
 立即注册
查看: 1833|回复: 2

getchar()跟ch = getchar()的区别在哪?

[复制链接]
发表于 2021-10-9 15:58:04 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
我一开始写了下面的代码,点击回车后只是换了行,还要再按一次回车才输出结果,结果还是错的。
  1. #include <stdio.h>
  2. #include <ctype.h>

  3. int main(void)
  4. {
  5.         //输入英文字母,计算对应值的总和
  6.         const int letter_count[26] = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10};
  7.         int scrabble = 0;
  8.        
  9.         printf("Enter a word: ");
  10.        
  11.         while (getchar() != '\n') {
  12.                 scrabble += letter_count[toupper(getchar()) - 'A'];
  13.         }
  14.        
  15.         printf("Scrabble value: %d\n", scrabble);
  16.        
  17.         return 0;
  18. }
复制代码


后面我改成ch = getchar()之后就正常了,这是为什么?这两个不一样吗?改之后的代码如下:
  1. #include <stdio.h>
  2. #include <ctype.h>

  3. int main(void)
  4. {
  5.         //输入英文字母,计算对应值的总和
  6.         const int letter_count[26] = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10};
  7.         int scrabble = 0;
  8.         char ch;
  9.        
  10.         printf("Enter a word: ");
  11.        
  12.         while ((ch = getchar()) != '\n') {
  13.                 scrabble += letter_count[toupper(ch) - 'A'];
  14.         }
  15.        
  16.         printf("Scrabble value: %d\n", scrabble);
  17.        
  18.         return 0;
  19. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-10-9 16:18:54 | 显示全部楼层
while (getchar() != '\n')  只是做判断真假
while ((ch = getchar()) != '\n')  做两件事,赋值和做判断
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-10-9 18:53:43 | 显示全部楼层
你每调用一次getchar,就会接收一个字符
不然怎么分辨你是想用刚才输入的字符还是再接收一个字符?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-29 16:42

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表