gpt4 book ai didi

c - 使用 getchar() 时的额外循环和 getchar() 的行为

转载 作者:太空宇宙 更新时间:2023-11-04 01:35:14 27 4
gpt4 key购买 nike

当我想弄清楚 getchar() 到底做了什么时,这一小段 loop 确实让我感到困惑。

int i;
int c;
for (i = 0; i < 100; i++) {
c = getchar();
printf("%d\n", c);
printf("i is %d\n", i);
}

输入输出为:

input: 1
output:
49
i is 0
10
i is 1

input: 12
output:
49
i is 2
50
i is 3
10
i is 4

正如我之前设想的那样,如果我输入 1 个字符,getchar() 应该将其提取出来,而 putchar() 将打印它,然后程序转到下一个循环并等待我的下一个输入。但是结果似乎表明代码并没有像我想象的那样工作:

  1. 输出数字是什么意思?
  2. 总是有一个额外的循环打印10,这个10是什么意思?如果它表示 EOF,为什么在循环中将 c = getchar(); 替换为 c = (getchar() != EOF); , 代码总是打印 1 ,正如我所想的那样,应该在最后一个循环中打印 0

非常感谢!

最佳答案

Question

What do the output numbers mean?

输出数字是指根据你的字符集你的字符的值,通常基于ASCII (一些大型机也使用 EDCDIC )。

C11 (n1570), § 5.2.1 Character sets

Two sets of characters and their associated collating sequences shall be defined: the set in which source files are written (the source character set), and the set interpreted in the execution environment (the execution character set). Each set is further divided into a basic character set, whose contents are given by this subclause, and a set of zero or more locale-specific members (which are not members of the basic character set) called extended characters. The combined set is also called the extended character set. The values of the members of the execution character set are implementation-defined.

因此,通过这种字符编码,49就是字符'1' 50 是字符 '2' .

Question

There is always an extra loop printing 10, what does this 10 mean?

对于 ASCII 字符集,10 是换行符 '\n' .

当您键入字符 '1' 时在你的键盘上,标准输入流 stdin实际上会收到两个字符:'1''\n' , 因为你按的是 <Enter>验证您的输入。

因此,您应该在完成 getchar 后清理标准输入流称呼。实现它的一种可能方法是消耗每个字符,直到到达换行符或 EOF :

#include <stdio.h>

int c;

while ((c = getchar()) != '\n' && c != EOF)
;

在 BSD 上,还有函数 fpurge并且,在 Solaris 和 GNU/Linux 上,__fpurge可用。

Question

If it means EOF, why after replacing c = getchar(); with c = (getchar() != EOF); within the loop, the code always print 1 which, as I supposed, should print a 0 in the last loop?

EOF 的值不能是 10,因为 EOF必须具有负值。

C11 (n1570), § 7.21.1 Introduction

EOF, which expands to an integer constant expression, with type int and a negative value [...].

关于c - 使用 getchar() 时的额外循环和 getchar() 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15600349/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com