[英]C Simple Code Involving getchar() and putchar() Unexpected Output
當我按照書中的示例進行操作時,
#include <stdio.h>
main()
{
int c;
c = getchar();
while (c != EOF) {
putchar(c)
c = getchar();
}
}
我認為首先讀取字符會更有意義,然后打印它以便切換 putchar 和 getchar
c = getchar();
putchar(c);
現在當我運行它時,putchar 的第一個 output 缺少 c 的第一個字符會發生什么? 這是 output:
kingvon@KingVon:~/Desktop/C$ ./a.out
first letter is missing?
irst letter is missing?
but now it is not
but now it is not
這很有趣,為什么會發生這種情況?
因為你在循環之前得到了一個角色。 這意味着 c 等於第一個字符,但在循環中它會獲取之后的每個字符。 所以,
Get: f
Start the loop
Get: i
Print: i
And so on
問題是現在您不打印在循環之前使用getchar()
讀取的字符,因此您不打印第一個字符。
如果您想先執行getchar()
,請將其放入while()
條件。
#include <stdio.h>
main()
{
int c;
while ((c = getchar()) != EOF) {
putchar(c)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.