Thread: why does every character get printed twice?

  1. #1
    Registered User
    Join Date
    Sep 2010
    Location
    Europe
    Posts
    87

    why does every character get printed twice?

    I am working on a program that prints "How are you?" on the screen by printing byte by byte.

    First I wrote

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    int main()
    {
           putchar(72);
           putchar(111);
           putchar(119);
           putchar(32);
           putchar(97);
           putchar(114);
           putchar(101);
           putchar(32);
           putchar(121);
           putchar(111);
           putchar(117);
           putchar(63);
       return 0;
    }
    And the output was exactly what was expected.

    Now I wrote

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    int main()
    {
        unsigned char t[20];
        t[0]=72;
        t[1]=111;
        t[2]=119;
        t[3]=32;
        t[4]=97;
        t[5]=114;
        t[6]=101;
        t[7]=32;
        t[8]=121;
        t[9]=111;
        t[10]=117;
        t[11]=63;
        int i;
        for(i=0;i<12;i++)
            {
                printf("%c",putchar(t[i]));
            }
        return 0;
    }
    and the output is: HHooww aarree yyoouu??

    Why?

    EDIT:

    I have it, there should be just the

    Code:
        for(i=0;i<12;i++)
            {
                putchar(t[i]);
            }
    Last edited by nerio; 01-24-2016 at 04:59 AM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,068
    > and the output is: HHooww aarree yyoouu??
    > Why?
    Because you're calling printf AND putchar at the same time.

    Since putchar() returns the character printed, it also gets printed again though the %c format of printf.

    Use one or the other.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Jun 2011
    Posts
    4,509
    You should be using character literals instead of magic numbers; e.g.

    Code:
    putchar('H');
    
    // instead of...
    
    putchar(72);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Why Garbage value is getting printed???
    By Siddarth777 in forum C Programming
    Replies: 3
    Last Post: 08-16-2012, 11:12 AM
  2. Moving a printed character
    By george7378 in forum C++ Programming
    Replies: 13
    Last Post: 02-28-2010, 12:34 AM
  3. Replies: 8
    Last Post: 11-12-2008, 11:25 AM
  4. int wrong value being printed?
    By Axel in forum C Programming
    Replies: 11
    Last Post: 10-14-2006, 01:37 AM
  5. Why one character size but two printed on screen
    By intmail in forum Linux Programming
    Replies: 3
    Last Post: 08-09-2006, 08:02 AM