Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

[c] integer to character

  1. Oct 22, 2012 #1
    Ok so I was trying something in C when i found something i don't understand:-
    code is:-
    int c = 1;
    printf("%c\n",c);
    (not writing the include and return 0 stuff)

    so when i run this it gives an output of a 2x2 box like this:-
    0 0
    0 1

    whats happening. When i put the 1 in commas like this int c= '1' then it gives an ouput 1. Thats good but when i dont put the comma it gives this box, why?
     
  2. jcsd
  3. Oct 22, 2012 #2

    Mark44

    Staff: Mentor

    I don't understand what you're talking about with the 2x2 box...

    In C a character is a number: specifically, the value of a character is its ASCII code. Some characters, such as those whose ASCII codes are in the range 0 - 31, are nonprinting control characters.

    There is a difference between the number 1 and the numeric character '1'. The value of the first is 1, of course, but the value of '1' is 49.

    You can convince yourself of this by running this code.
    Code (Text):

    printf("%c\n", 1);  // You won't see anything on the screen.
    printf("%d\n", '1'); // Should print 49.
     
    BTW, this-- , -- is a comma. This -- ' -- is a single quote.
     
  4. Oct 22, 2012 #3
    oh sorry about the single quote and comma error

    printf("%c\n",1); prints the box.
    I tried it - on linux (ubuntu) with GCC (if that matters)
     
  5. Oct 22, 2012 #4
    The 'box' you are seeing is what happens when you print one of the non-printable ASCII chars.

    int c = 1; // assign a new int the value 1
    int c = '1'; // assign a new int the integer value of the character '1' (which is 49)

    printf("%c", c); // print the character representation of the integer variable c
    printf("%d", c); // print the integer representation of the integer variable c

    Have a look at the ASCII table. Notice that the integer 1 represents the SOH (start of heading) character which is not printable. If you want to print the number one as stored in your integer variable, you should use the %d format specifier not %c.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook