Interleaving of putchar() and printf() functions

It is a statement given in K&R that printf() and putchar() can be interleaved. If it true then why is the following code not giving the required output:-


    #include"stdio.h"
    void main()
    {
    char c,d;
    printf("Enter the first charactern");
    scanf("%c",&c);
    printf("%cn",c);
    printf("Enter the second charactern");
    d=getchar();
    putchar(d);
    printf("n");
    }

Whenever I am executing this program, the output is as follows:-

Enter the first character
a
a
Enter the second character


This is the output. This is also happening if I replace printf() by putchar() and scanf() by getchar(). Why is this happpening?


The first scanf leaves in the input buffer the n resulting from the Return press, so your second getchar() will acquire this n instead of acquiring another character from the user.

If you want to skip that newline character, you can either instruct the scanf to "eat" it:

scanf("%cn",&c);

or "eat it" directly with a call to getchar() :

scanf("%c",&c);
getchar();

(notice that these are not exactly equivalent, since the second snippet will eat whatever character happens to be in the buffer, while the first one will remove it only if it's a n )


你可以像这样纠正你的代码:

#include <stdio.h>

int main() {
    char c, d;
    printf("Enter the first charactern");
    scanf("%cn", &c);    // Ask scanf to read newline and skip
    printf("%cn", c);

    printf("Enter the second charactern");
    d = getchar();
    putchar(d);
    printf("n");
    return 0;
}

你得到两个a,因为你输入了一个与控制台相呼应然后打印出来的a。

链接地址: http://www.djcxy.com/p/72168.html

上一篇: 将类型化数组返回到主函数

下一篇: 交织putchar()和printf()函数