printf 打印额外的“D"getchar() 调用后 [英] printf printing extra "D" after getchar() call

查看:61
本文介绍了printf 打印额外的“D"getchar() 调用后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试研究C 编程语言",但遇到了 printf 和 EOF 字符的一些问题.我正在使用 mac 终端并使用 clang 进行编译.

I'm trying to work through "The C Programming Language", and I'm running into some issues with printf and the EOF character. I'm working the the mac terminal and compiling with clang.

运行此代码:

#include <stdio.h>

main()
{
    int val;
    while ((val = getchar()) != EOF)
        printf("%d\n", val);
    /*val = 5;*/
    /*printf("hi\n");*/
    /*printf("%d\n", val);*/
    printf("%d\n", val);
}

像我期望的那样工作,阻塞直到我输入一个字符然后打印:"*character code*\n10\n",除了 ctrl-d,打印 "-1" 然后退出.

works like I would expect, blocking till I enter a character then printing: "*character code*\n10\n", except for ctrl-d, which prints "-1" then exits.

然而,在取消注释 "val = 5;" 语句后,输入 "ctrl-d" 会导致它打印:"5D".

After uncommenting the "val = 5;" statement however, entering "ctrl-d" causes it to print: "5D".

我弄乱了它,发现第二次打印 val(第三条注释语句)只会导致 one "D": "5D\n5",并且在之前打印一个常量变量(第二个注释语句)阻止D"出现:"hi\n5\n5".

I messed around with it and found that printing val a second time (the third commented statement) will result in only one "D": "5D\n5", and that printing a constant before the variables (the second commented statement) stops the "D" from appearing: "hi\n5\n5".

我绝对不想要 D,如果有人能解释如何删除它,我将不胜感激.

I absolutely do not want the D and if anyone could explain how to remove it, I would be very grateful.

推荐答案

因此,控制台输入正在打印您键入的内容.就像你输入字母 A 一样,字母 A 会被打印出来.CTRL-D 作为 ^D 打印到标准输出.

So, what happens is the console input is printing what you type. Just like if you type the letter A, the letter A gets printed. The CTRL-D gets printed to the stdout as ^D.

如果打印出 1 个字符,^ 将被覆盖.如果打印出 2 个字符,^ 和 D 都会被覆盖.所以,-1 覆盖它,hi 覆盖它,但 1 个字符不会.

If you print out 1 character, the ^ is overwritten. If you print out 2 characters, both the ^ and D are overwritten. So, -1 overwrites it, hi overwrites it, but 1 character will not.

这篇关于printf 打印额外的“D"getchar() 调用后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆