程序在每次输入后打印一个值为10的额外行

Tel*_*tha 2 c printf getchar

我有这个简单的程序:

#include <stdio.h>

int main()
{
    int c;
    while ( ( c = getchar()) != EOF)
        printf("%d %c\n", c, c);

    return 1; 
}
Run Code Online (Sandbox Code Playgroud)

但是由于某些原因,在执行时我最终获得了额外的值10:

a
97 a
10 

b
98 b
10 

abc
97 a
98 b
99 c
10 
Run Code Online (Sandbox Code Playgroud)

什么是价值10,它来自哪里?如何阻止它发生?

解:

#include <stdio.h>
#include <ctype.h>

int main()
{
    int c;
    while ( ( c = getchar()) != EOF)
    {
        if ( isprint (c))
        {
            printf("%d %c\n", c, c);
        }
    }

    return 1; 
}
Run Code Online (Sandbox Code Playgroud)

Som*_*ude 6

这是您为输入输入的换行符.它的ASCII值为10.

以下是"停止"它的三种方法:

  1. if在循环中添加一个检查以检查它,并仅在它不是换行符时打印.

  2. 使用fgets一次读取一个整条生产线,从字符串(去除换行fgets增加了它),并遍历字符串并打印每个字符.

  3. 使用scanf读取一个字符.如果格式中有前导空格,它将跳过像换行符这样的空格.

第一种方法也可用于检查不可打印的字符(请参阅参考资料isprint),以及其他类别的字符(如果要对它们进行特殊打印)(请查看这些字符分类函数).