1.5.1 file copying

Get inputs from related service,like keyboard,and then copy what you get to the output,like screen.

/*1.5.1 file copying – original version*/

#include <stdio.h>
main()
{
    int c = 0;
    c = getchar();
    while (c != EOF)
    {
        putchar(c);
        c = getchar();
    }
}

There’s something interesting here,we’ve learned printf() before,if we use it here,what will happen?

/*1.5.1 file copying*/

#include <stdio.h>
main()
{
    int c = 0;
    c = getchar();
    while (c != EOF)
    {
        c = getchar();
        printf("%d\n",c);
    }
}

The output of this program display input characters’ ASCII code instead of its original value and this is something different from putchar().
But I still have a question about it.It works alright but I’m afraid at the first input,it will return something,as far as I’m concerned,not properly designed.
If I type in one character,’1’ or ‘a’ for example,it will eventually give me a ‘10’,which,in the ASCII code,stands for Null;
11

and if I type in a string,’abcdef’ for instance,it will feedback every character’s ASCII code properly but lacks the last one’s own ASCII code instead of 10,which stands for a Null character;
1

if I type in nothing but only give an ‘Enter’,it will feedback nothing at all.
 
All the phenomenon above only exist at the first typing in,while at the next that follow,it will feedback properly.
As far as I am concerned,every character,no matter one character or a string,is terminated with a ‘’ whose ASCII code  is 10,but why the program fail to give input’s own ASCII code instead of only showing a ‘’\o’ ‘s?

用printf()替代putchar()之后,运行程序出现了一个比较有趣的问题。
第一次出入的字符总会得到错误的结果:如果输入单个字符,则只会返回10,而10在ASCII码中代表的是空位符;如果输入一个字符串,则字符串中最后一位字符的ASCII码无法得到,取而代之的还是一个10;如果什么也不输入,而只回车的话,就会什么也不得到。
然而上面这些现象在第二次输入时就不再出现了,所有的输入都得到想要的结果,当然,第二次输入回车还是会返回一个10.

现在我所掌握掌握的知识是,一个字符串,无论是单个字符还是一连串的字符,都是以结尾的,所以上面显示的10正是这个字符,可是为什么第一次输入的时候会出现错误呢?

Leave a comment