Search

2.7 — Chars

Even though the char data type is an integer (and thus follows all of the normal integer rules), we typically work with chars in a different way than normal integers. A char variable holds a 1-byte integer. However, instead of interpreting the value of the char as an integer, the value of a char variable is typically interpreted as an ASCII character.

ASCII stands for American Standard Code for Information Interchange, and it defines a particular way to represent English characters (plus a few other symbols) as numbers between 0 and 127 (called a code or code point). For instance, the character ‘a’ is code 97. ‘b’ is code 98. Characters are always placed between single quotes.

Here’s a full table of ASCII characters:

Code Symbol Code Symbol Code Symbol Code Symbol
0 NUL (null) 32 (space) 64 @ 96 `
1 SOH (start of header) 33 ! 65 A 97 a
2 STX (start of text) 34 66 B 98 b
3 ETX (end of text) 35 # 67 C 99 c
4 EOT (end of transmission) 36 $ 68 D 100 d
5 ENQ (enquiry) 37 % 69 E 101 e
6 ACK (acknowledge) 38 & 70 F 102 f
7 BEL (bell) 39 71 G 103 g
8 BS (backspace) 40 ( 72 H 104 h
9 HT (horizontal tab) 41 ) 73 I 105 i
10 LF (line feed/new line) 42 * 74 J 106 j
11 VT (vertical tab) 43 + 75 K 107 k
12 FF (form feed / new page) 44 , 76 L 108 l
13 CR (carriage return) 45 - 77 M 109 m
14 SO (shift out) 46 . 78 N 110 n
15 SI (shift in) 47 / 79 O 111 o
16 DLE (data link escape) 48 0 80 P 112 p
17 DC1 (data control 1) 49 1 81 Q 113 q
18 DC2 (data control 2) 50 2 82 R 114 r
19 DC3 (data control 3) 51 3 83 S 115 s
20 DC4 (data control 4) 52 4 84 T 116 t
21 NAK (negative acknowledge) 53 5 85 U 117 u
22 SYN (synchronous idle) 54 6 86 V 118 v
23 ETB (end of transmission block) 55 7 87 W 119 w
24 CAN (cancel) 56 8 88 X 120 x
25 EM (end of medium) 57 9 89 Y 121 y
26 SUB (substitute) 58 : 90 Z 122 z
27 ESC (escape) 59 ; 91 [ 123 {
28 FS (file separator) 60 < 92 \ 124 |
29 GS (group separator) 61 = 93 ] 125 }
30 RS (record separator) 62 > 94 ^ 126 ~
31 US (unit separator) 63 ? 95 _ 127 DEL (delete)

Codes 0-31 are called the unprintable chars, and they’re mostly used to do formatting and control printers. Most of these are obsolete now.

Codes 32-127 are called the printable characters, and they represent the letters, numbers, and punctuation that most computers use to display basic English text.

The following two initializations both initialize the char with integer value 97:

One word of caution: be careful not to mix up character (keyboard) numbers with actual numbers. The following two initializations are not the same

Printing chars

When using cout to print a char, cout outputs the char variable as an ASCII character instead of a number:

This produces the result:

a

We can also output char literals directly:

This produces the result:

b

Note: The fixed width integer int8_t is usually treated the same as a signed char in C++, so it will generally print as a char instead of an integer.

Printing chars as integers via type casting

If we want to output a char as a number instead of a character, we have to tell cout to print the char as if it were an integer. One (poor) way to do this is by assigning the char to an integer, and printing the integer:

However, this is clunky. A better way is to use a type cast. A type cast creates a value of one type from a value of another type. To convert between fundamental data types (for example, from a char to an int, or vice versa), we use a type cast called a static cast.

The syntax for the static cast looks a little funny:

static_cast<new_type>(expression)

static_cast takes the value from an expression as input, and converts it into whatever fundamental type new_type represents (e.g. int, boolean, char, double).

Here’s using a static cast to create an integer value from our char value:

This results in:

a
97
a

It’s important to note that static_cast takes an expression as input. When we pass in a variable, that variable is evaluated to produce its value, which is then converted to the new type. The variable is not affected by casting its value. In the above case, ch is still a char, and still holds the same value.

Also note that static casting doesn’t do any range checking, so if you cast an integer that is too big to fit into a char, you’ll overflow your char.

We’ll talk more about static casts and the different types of casts in a future lesson.

Inputting chars

The following program asks the user to input a character, then prints out both the character and its ASCII code:

Here’s the output from one run:

Input a keyboard character: q
q has ASCII code 113

Note that even though cin will let you enter multiple characters, ch will only hold 1 character. Consequently, only the first input character is placed in ch. The rest of the user input is left in the input buffer that cin uses, and can be accessed with subsequent calls to cin.

You can see this behavior in the following example:

Input a keyboard character: abcd
a has ASCII code 97
b has ASCII code 98

Char size, range, and default sign

Char is defined by C++ to always be one byte in size. By default, a char may be signed or unsigned (though it’s usually signed). If you’re using chars to hold ASCII characters, you don’t need to specify a sign (since both signed and unsigned chars can hold values between 0 and 127).

If you’re using a char to hold small integers, you should always specify whether it is signed or unsigned. A signed char can hold a number between -128 and 127. An unsigned char can hold a number between 0 and 255.

Escape sequences

C++ has some characters that have special meaning. These characters are called escape sequences. An escape sequence starts with a ‘\’ (backslash) , and then a following letter or number.

The most common escape sequence is ‘\n’, which can be used to embed a newline in a string of text:

This outputs:

First line
Second line

Another commonly used escape sequence is ‘\t’, which embeds a tab:

Which outputs:

First part        Second part

Three other notable escape sequences are:
\’ prints a single quote
\” prints a double quote
\\ prints a backslash

Here’s a table of all of the escape sequences:

Name Symbol Meaning
Alert \a Makes an alert, such as a beep
Backspace \b Moves the cursor back one space
Formfeed \f Moves the cursor to next logical page
Newline \n Moves cursor to next line
Carriage return \r Moves cursor to beginning of line
Horizontal tab \t Prints a horizontal tab
Vertical tab \v Prints a vertical tab
Single quote \’ Prints a single quote
Double quote \” Prints a double quote
Backslash \\ Prints a backslash
Question mark \? Prints a question mark
Octal number \(number) Translates into char represented by octal
Hex number \x(number) Translates into char represented by hex number

Here are some examples:

Prints:

"This is quoted text"
This string contains a single backslash \
6F in hex is char 'o'

Newline (\n) vs. std::endl -- which should you use?

You may have noticed in the last example that we can use \n to move the cursor to the next line, which appears to duplicate the functionality of std::endl. However, they are slightly different.

When std::cout is used for output, the output may be buffered -- that is, std::cout may not send the text to the output device immediately (for performance reasons). Both ‘\n’ and std::endl will move the cursor to the next line. In addition, std::endl will also ensure that any queued output is actually output before continuing.

So when should you use ‘\n’ vs std::endl? The short answer is:

  • Use std::endl when you need to ensure your output is output immediately (e.g. when writing a record to a file, or when updating a progress bar). Note that this may have a performance cost, particularly if writing to the output device is slow (e.g. when writing a file to a disk).
  • Use ‘\n’ in other cases.

(Administrative note: Throughout the rest of this tutorial, we’ve used std::endl;. We’re in the process of converting over to ‘\n’ because for console output, this is almost always the better choice.)

What about the other char types, wchar_t, char16_t, and char32_t?

wchar_t should be avoided in almost all cases (except when interfacing with the Windows API). Its size is implementation defined, and is not reliable. It has largely been deprecated.

Much like ASCII maps the integers 0-127 to American English characters, other character encoding standards exist to map integers (of varying sizes) to characters in other languages. The most well-known mapping outside of ASCII is the Unicode standard, which maps over 110,000 integers to characters in many different languages. Because Unicode contains so many code points, a single Unicode code point needs 32-bits to represent a character (called UTF-32). However, Unicode characters can also be encoded using multiple 16-bit or 8-bit characters (called UTF-16 and UTF-8 respectively).

char16_t and char32_t were added to C++11 to provide explicit support for 16-bit and 32-bit Unicode characters (8-bit Unicode characters are already supported by the normal char type).

You won’t need to use char16_t or char32_t unless you’re planning on making your program Unicode compatible and you are using 16-bit or 32-bit Unicode characters. Unicode and localization is generally outside the scope of these tutorials, so we won’t cover it further.

What’s the difference between putting symbols in single and double quotes?

As you learned above, chars are always put in single quotes (e.g. ‘a’, ‘+’, ‘5’). A char can only represent one symbol (e.g. the letter a, the plus symbol, the number 5). Something like this is illegal:

Text put between double quotes is called a string (e.g. “Hello, world!”). A string is a collection of sequential characters (and thus, a string can hold multiple symbols).

For now, you’re welcome to use string literals in your code:

However, string variables are a little more complex than chars or the fundamental data types, so we’ll reserve discussion of those until later.

2.8 -- Literals
Index
2.6 -- Boolean values and an introduction to if statements

92 comments to 2.7 — Chars

  • Jeffey

    I made a program that makes a ASCII chart. Even though you can find this chart in almost any place dealing with coding. I thought it be fun to make my own reference.

    Code
    #include "stdafx.h"
    #include <iostream>

    int main()
    {
    using namespace std;
    for(unsigned char nCount = 1; nCount <= 127; nCount++)
    {
    if (nCount <= 127)
    cout << (int)nCount << " : " << nCount << endl;
    }
    return 0;
    }

    • Jeffey

      Oh! you may notice that nCount should be ucCount…thats because when I first wrote the program, it was an exercise that just counted up from 0. I just changed the int integer(int) to a char integer (unsigned char). Leaving the variable the same. Technicality there nothing wrong with that. However if you copy this program. I would suggest trying to use Hungarian Notion the correct way.

    • See ++

      Hi Jeffey. Nice idea to construct such a code. Actually you don’t need to use the hypothetical statement if. I simplified your code:

  • Pathik

    Why do you need ‘/?’…. we can use question mark with cout….

    • Honestly, I don’t know. 🙂

      • PReinie

        From my years of C coding, single quotes enclose one character and double-quotes enclose a string. Strings were (are?) far different than a char - mostly in storage (memory) and using them. Strings are one or more characters and terminated (usually with a zero - not the character 0, but all zero bits). Strings always take up more than 8 bits (one byte).
        cout may not care, but your variable declaration (compiler) may be particular about it and/or your code may not work.

        The slash question mark may be used in case a compiler interprets question marks as something else. This depends on your compiler, IE, it’s just to make sure your code really does (compiles to) what you want it to do. Some pattern matching (MS Word?) use a question mark to substitute/match a single character, and to match a question mark you have to escape it. Same thing may be for some compilers.

  • Shawn

    Ok, i tried the /v for form feed, which in my case could be represented as a new page(would feed lines until the text shown would be gone. But instead it read out as the male gender sign as a character. I just dont want to have to input like 15 /n’s to make the same effect. I know an alternative is to make 15 /n’s a char constant and just input it when i need a new page but im just wondering if im just doing something wrong. Help, please! 😛

    • I’ve never tried using the form feed char. I doubt it works on a monitor, though it might still work in printers… maybe.

      You can’t stick 15 /n’s in a char because a char only holds one character, not 15. If you want 15 spaces, for now you’ll have to do 15 cout << "\n"; until you learn how to do loops.

      • James

        I was just reading through the comments on this excellent tutorial.

        If you want to wipe the text off the terminal you can use the clear screen command, system(“cls”)

        Hope This is what you were lookign for! 🙂

        • Alex

          This solution will only work on some operating systems and is not recommended. system() makes a call to the operating system and runs the program “cls”, which happens to clear the console on Windows. But it won’t work on Unix, since Unix doesn’t have an executable named cls.

  • Vlad

    I tried declaring a variable as

    but it didn’t work, how can i create a string variable

  • Bry

    Hi. Been having fun going through this tutorial. I was just compiling the ASCII code…

    It gave me a warning with visual c++ 2008 express until I changed the top line to…

    Thanks for creating this tutorial! 🙂

  • prabhakar

    respected ALEX, i have been deligently and sincerely trying to follow your “lessons”.
    i tried to compile one code re. CHAR.
    I AM NOT GETTING THE RESULTS AS PROJECTED BY U.

    [One word of caution: be careful not to mix up character (keyboard) numbers with actual numbers. The following two assignments are not the same

    view sourceprint?
    1.
    char chValue = ‘5’; // assigns 53 (ASCII code for ‘5’)
    2.
    char chValue2 = 5; // assigns 5 ]

    What ‘cout’ gives me is

    a)5 for chValue
    b)a sign like “club in playing cards”

    please advise me--thanks prabhakar

    • Alex

      If you print char 53, you’ll get the character ‘5’.
      If you print char 5, you’ll get the “club in playing cards” on Windows, because the font that Windows uses in the console has this club symbol mapped to code point 5. Why? I guess Microsoft figured that putting a printable symbol at that code point was better than leaving something unprintable there.

      Note that this club symbol is not a standard part of ASCII and will not work on other operating systems, like Unix.

  • PReinie

    Alex, thanks for the info!

    From my background I’ve used binary, octal, hex and decimal when referring to characters, so please make sure above when you say an ‘a’ is 97 you specify that it’s (it is) a decimal 97. Granted the compiler assumes decimal, but readers may not.

    Also, “The following program asks the user to input a character, then prints out both the character and it’s ASCII code:” Please check in all the tutorials each use of “it’s” which is short for “it is” and is never possessive. “its” is possessive just is his, hers and theirs are possessive and you do not use an apostrophe for them.

  • jsieckman

    In the following example above:

    char chValue = ‘5’; // assigns 53 (ASCII code for ‘5’)
    char chValue2 = 5; // assigns 5

    Does the bottom statement assign 5 or does it assign the character associated with the ASCII code for 5 (i.e. a club symbol)?

    Thanks

    • Alex

      The top statement assigns the character ‘5’ (integer 53), which is printed as ‘5’.
      The bottom statement assigns in the integer value 5, which is printed as a club symbol in the Windows console.

  • Jupi

    Do programmers have to memorize escape sequences and stuff? It would be helpful if there was a single page with all the reference tables in it.. I’ll just bookmark ’em for now (;

  • lan

    Please i need some help here.
    For example on these lines of code

    char = cchar;
    cin>> cchar;

    if i input 10 at cchar it stores 10 as a string or as an integer?

    i made the code below to make a test in order to get the
    answer on the question that is above

    char cchar;
    cin>>cchar;
    char cchar2 = 5;
    cout<<cchar+cchar2<<endl;
    cout<<cchar+(int)cchar2;

    i input 5 and it gives me a sum of 58
    on both couts, this make me understand that it takes
    the input of cchar as string because as you said in the tutorial:
    char chValue = '5'; // assigns 53 (ASCII code for '5')
    but i cant understand why at the second cout it takes (int)cchar2 as 53 shouldnt it have the value of 5 because of the (int).
    Please an answer would be appreciated.

    • You answered your own question - it stores 53, because as you said, it stores the ASCII code. when you add the (int), nothing changes, because cchar2 already has an int in it (53), hence it still thinks of it as 53.

  • dice3000

    cout << "\a";

    best thing ever 😀

  • werthkew

    Can anyone tell me why the following program prints “-128” to the screen for chValue2?

    #include

    char chValue1 = ‘a’;
    char chValue2 = 128;

    int main()
    {
    using namespace std;
    cout << chValue1 << endl;
    cout << (int)chValue2 << endl;
    return 0;
    }

    • Xanth

      A char variable is only one byte, which means it can only hold 256 values. If it’s signed (most compilers automatically sign variables) that means it can only hold integers from -128 to 127. If you unsign the variable using the unsigned command it’ll be able to hold integers from 0 to 255. I ran the program to test it and if you unsign your char variable it works like a charm as long as you don’t assign it anything higher than 255.

    • Alex

      Your chars are apparently signed by default (which is common).

      128 is outside the range for signed chars, so you’re overflowing your char and it’s wrapping around to the next number, which is -128.

      When you cast -128 to an int (also signed by default), cout prints it as -128.

  • Hey

    Thanks for this tut, it’s very useful for me.

    First; after title “Escape sequences” in line 2 you wrote \\. should not that be \?

    Second; can you bring an example for \(number)?

    • Alex

      Fixed and done. I used the hex escape code instead of the octal escape code because hex is more commonly used in programming than octal. I can’t remember the last time I used octal.

  • Jeremy

    You can also print a char as a number using "integral promotion". Basically a unary + or - operator to the left of the variable:

    #include <iostream>

    int main()
    {
        char chLetter = ‘a’;

        std::cout << chLetter << std::endl;

        // the unary + operator gives the integer value of a char:
        std::cout << +chLetter << std::endl;

        // the unary - operation gives the negative integer value of a char:
        std::cout << -chLetter << std::endl;

        // integral promotions are "value preserving" and do not change the value of the variable:
        std::cout << chLetter << std::endl;

        return 0;
    }

  • I think there is typo in the sentence below(should be ‘char’ instead of ‘chat’):

    "The following two initializations both initialize the chat with integer value 97:"

    Also, the syntax for static_cast could have been(just saying):
    static_cast(expression)

  • Dan Downs

    Your introduction to ASCII took me back decades, when ASCII was new and slowly replacing Baudot code used by teletypes. I was an AF communications tech, we still had tube equipment while integrated circuits were coming out and the biggest fastest communications terminal we had was the IBM 360 to do a job done by a single chip today. Some of those characters below char(32) were vital to digital transmission, which consisted of 80 character blocks transmitted synchronously at speeds up to 1200 baud (about 1.2 kB/s) using very expensive modems. SOH, ETX, EOM, ACK NAK and SYN for example were critical at the time. Of course they are obsolete but they certainly played an important roll in their day.  Thanks for the memories.  The tutorial is very good, thank you.

  • Twisted Code

    Why does the questionmark character have an escape sequence? Does "?" do something special in a string or character-typed object? If so, what chapter can I jump to to find out more?

  • Alex

    I want to tell you how much I appreciate this tutorial - and ask one question/clarification.

    I am just learning C++ so I can create a stand-alone application for my daughter.  I have previously coded in php, bash, java and html, but this is my first crack at a compiled program.  I (as usual) just dove in and started trying some things (usually worked best for me) but found numerous topics in C++ confusing so started looking for more help.

    I found this site and it has been wonderful!  It lets me learn by trying - something I like to do - AND it explains the why of things - something I need to really learn something.  

    Thank you.  

    I do have one question.

    In the example above where you have:

    is that supposed to be:

    If so, I understand what you are saying.

    If not, I am not sure what you are getting at.

    Thanks again for making this interesting, informative and educational.

    R

    • Damien

      Hey Ramblin
      I am just learning also but I think the way it shows is correct.

      I don’t think Alex was trying to illustrate that they will both print the same. In fact I think he was trying to show how the use of the single quotes changes the value that is initialised.

  • Aditya

    Even if the value of ‘op’ the user enters is not ;+; or ‘-‘, i do not get the invalid operator output. It assumes op=- and caries out subtraction
    I understand that i could use switch case to get the desired result, I am curious as to why this fails.

    Thanks!

  • Todd

    Typos.

    "When using cout to print a char, cout outputs the char variable as an ASCII characters (character) instead of a number"

    "The rest of the user input is left in the input buffer that cin uses, and can be access (accessed) with subsequent calls to cin."

  • AK

    You have suggested to use std::endl when you need to ensure your output is output immediately and use ‘\n’ in other cases.

    But I see the both are line buffered. i.e., both output the full output buffer when used.

    • Alex

      When printing to a console, this is generally true. However, when writing to disk, ‘\n’ may not cause any buffered input to be written to disk immediately, whereas std::end will.

  • Robin

    Where you say
    static_cast<new_type>(expression)
    the <new_type> gets parsed as html and is not showing
    using static_cast&lt;new_type&gt;(expression) would fix this

  • The Razer

    is string a char type ?
    for example :

    can you explane a little about this variable type ?

    • Alex

      string isn’t a char type. string is a special type of object called a class, and explaining classes at this point would be complicated.

      You can think of a string as a sequential collection of chars (each character in “qwerty” is a char).

  • "cout outputs the char variable as an ASCII character instead of a number", Alex please tell me how cin takes input from a user. As an ASCII code or simple keyboard character. This program is a bit tricky for me:

    Suppose someone entered 9 as input for variable ch. When cout is printing result, 9 remains 9 (before static_cast) and cout does not interpret it as  ASCII code. When cin is removed from the program and ch is given a value like this:

    It produces "b has ASCII code 98". Sorry, if I am so stupid, but why results are different in above cases. Does cin takes input in this form:

    One more thing. When I assign 98 with single quotes to a char variable (char ch(’98’)), my compiler warns me that the variable is given a multi-character constant. On running the program, cout only prints the last digit (e.g. 8 for 98). Why so?

    • Alex

      In your top example, ch is of type char, so when the user inputs ‘9’, “cin >> ch” will treat the user input as ‘9’ (the character) and not 9 (the integer).

      If you had defined ch as an int, “cin >> ch” would have treated the input as 9 (the integer) instead. If ch was defined as a string, “cin >> ch” would have treated the input as “9” (the string) instead.

      So, in other words, cin looks at the data type of the variable being input into, and infers what the most appropriate value should be from that.

      Remember that chars can only hold a single char. ’98’ is two chars, which is why you are getting a warning. Visual Studio at least seems to truncate this to the last character. I’m not sure why they made that decision instead of treating it as an error.

  • Amandeep

    I never use "return 0" at the end of my main() and my programs work fine. So why is it used in every program here? Are there some special cases where not using "return 0" will lead to errors or is it just a standard practice?

    • Alex

      In C++, the main function must return a value to the operating system. We typically return 0 to indicate that “the program ran okay”.

      Some compilers (such as Visual Studio) will let you omit the return value in main (they’ll return 0 for you), but best practice is not to rely on this.

  • Amandeep

    Why do these two declarations give different results while printing?
    char ch(‘8’);
    cout<< ch <<endl; //prints 8, as expected
    char32_t ch1(‘8’);
    cout<< ch1 <<endl; // prints code point for 8, that is, 56……why?????

    • Alex

      I can’t say for sure, but I can think of two possibilities. char32_t is supposed to be a distinct type, but:
      1) It’s possible your compiler has implemented char32_t as a typedef of integer, so cout is treating it as an integer for printing.
      2) It’s possible that cout has decided that char32_t should printed as an integer since the Windows console font is horrible doesn’t have support for most unicode code points.

      It’s worth noting that C++ really only has partial support for char16_t and char32_t. While there’s now a data type to hold the values, the iostream library doesn’t provide support for dealing with these types.

  • Abdullah Shwaiky

    Hello people I need some help in here

    I have a homework about the char, we didn’t take the lesson yet

    Here’s what he gave me:

    "I want you to try to code a program that does the following:
    - Define a variable of type "char".
    - Ask the user to enter a capital letter and store it in the variable (using cin).
    - Cout the variable.
    - Cout (the variable + 32) (Example: cout << c + 32 << endl).
    What do you notice? How can you explain this?"

    I have done everything correctly

    But I just can’t preview the small letter.

    Please help!!

  • shawn

    when i use v in the line

    then instead of working as a vertical tab v is replaced by a symbol in output string which is a ring wid a small arrow . I am using visual studio 2015. can u plz tell me the reason

  • Jim

    Alex,

    No big deal but your missing a std:: before endl here
    std::cout << "First linenSecond line" << endl;

    These may be dumb questions but is it pretty common to have extra data left in the input buffer? Would you ever want to do that in a program? If you can use endl to make sure the output buffer is emptied, is there a way make sure the input buffer is emptied? Would you ever need to do this?

    To me char,is probably one of the most confusing basic data types in C++. Since char can be both a number or a letter. Signed or unsigned and both can be the default.

    Do you ever have to use the word unsigned with char, isn’t char all you need?

    Since ASCII uses the positive signed char(int). How do you call out signed negatives -1 to-128?  

    In this lesson you initialized a char ch1(97)and char ch2(‘a’) and you wrote they both are the same 97. Isn’t int8_t(97) also the same?

    I’m still a bit confused as to when and where to us the code number(97)and the code character (‘a’). Is this right? if you initialize char with the code in the previous paragraph then cout will always outputs the (a) character, unless you assign it to an integer with int i(ch1), then
    it willprint out 97.

    • Alex

      Thanks for pointing out the typo. Fixed.

      Generally input being left in the input buffer is the result of the user entering something unexpected (e.g. a number instead of a letter or vice versa). In such cases, you’ll likely want to clean out the extraneous input, which you can do as follows:

      You can use unsigned char if you want, but I recommend you avoid it outside of very specific instances such as bit-fields.

      > Since ASCII uses the positive signed char(int). How do you call out signed negatives -1 to-128?

      I’m not sure what you’re asking here.

      In most cases, int8_t is treated the same as a signed char. But this isn’t guaranteed, so don’t depend on it!

      97 and ‘a’ are identical (both resolve to integer 97) -- however, you can use them contextually to provide the reader a clue as to your intent. Use 97 when you intend 97 to be a number, and ‘a’ when you intend ‘a’ to be treated as a character.

      • Jim

        Alex,
        Thanks for the quick reply.
        Maybe I’m reading to much into char and confusing myself. Since char is an integer aren’t all negative char just used as constants in the range of -1 to -128. What is the proper syntax to us? char(-128) or int(-128)?

        Can you show a couple of instance on how to use them maybe that will square me away?

        • Alex

          Yes, chars are integers and as such, you can assign integer values to them directly.

          You can also assign chars to them:

  • Nigel (still learning@50)

    Hello Alex,
    First off, thanks so much for the excellent lessons. I wrote the following prog :-

    # include <iostream>
    using namespace std;  
    void screenPrint(char ch)
       {
    cout << ch << " has the ASCII code "
    << static_cast<int>(ch) << endl;  
       }

    int main()
    {
    cout << "Enter No. of letters in your name..n";
    int num;
    cin >> num;
    cout << "Enter your Name..";
    char ch;
    cin >> ch;
        for (int x=1; x<=num; x++)
        {
          screenPrint(ch);
          cin >> ch; //Next letter in the queue.
        }
      return 0;
    …and was wondering. I initially had my void screenPrint() function as an ‘int’ function with a return 0; statement which also worked, despite it being passed the  character ‘ch’, is this, as i suspect because ch is  in fact  really
    an integer hence the ascii code or am i way off the mark and getting ahead of myself?
    Once again great website.
    just read the above blog so guessing that is why it works either way.

    • Alex

      Yes, chars are a type of integer, so they share most things in common with integers. C++ just treats chars differently in cases of printing because it knows you usually want the ASCII mapping, not the numeric value.

  • Domenic

    What surprised me was the behavior of this piece of code that seems to defy my understanding. This has no loop as a loop yet it works like one. I have start: and goto start. If I enter 1 character it spits out the results and then asks for input again. However if I input more than one character like a name it loops until the buffer is empty. Curious how that happens…

    • Alex

      There is a loop here: you’re using a goto statement to loop back to a previous statement.

      cin >> ch will extract a single character. If there are no characters waiting, it will ask the user to enter one. However, if there are characters that still have not been extracted (from the user entering multiple characters previously), it will instead extract the next character and continue without asking the user to enter more.

  • Maxwell Pollack

    THANK YOU ALEX!!  I love all of your tutorials.  They are really helpful.

  • Nyap

    typo
    "What’s the - different - between putting symbols in single and double quotes?" (should be difference)
    Last section

  • Rojava

    Hi! Can you tell me if there’s a difference between the two like performance-wise? They both seem to do the same thing.

    In the tutorial:

    What I’ve tried to do, but still does the same thing:

  • Chris

    For some reason, when the following code executes, the program prints out numbers where c3, c4, and c5 are explicitly used.  This problem does not occur, however with ASCII characters (‘!’ was tested).  I am useing Eclipse on Mac OS and am wondering how can I get the code bellow to print the Unicode characters represented as opposed to just their numeric value.

    • Alex

      It looks like your compiler is treating char16_t as an integer rather than a char to be printed. Since all of these characters are below 255, you could try casting them to an unsigned char and see if your console prints them. It may or may not, and if it does, it may not print the correct character (depending on what code page your console supports).

      Support for non-ascii characters (chars 128+) in C++ is surprisingly complicated, and localization-related topics would make a good tutorial topic in and of itself. 🙁

  • Abhishek

    Hi Alex, I wanted to know if you can increase the font size of the output window (that looks like cmd window). I am learning your tutorials through my laptop and the output is very small and my eyes hurt. I could change the font size of the codes and build log etc. Thank you!!

    • Alex

      Many consoles have the ability to set the font size. If you’re using windows, you can right click in the titlebar of the console window, choose properties, go to the font tab, and choose a larger font.

  • hsn

    Hi … why these source’a output is 5 ?
    I expect that the number 45 is displayed …

    #include<iostream>
    using namespace std;
    int main()
    {
    char n=’45’;
    cout<<n<<endl;

    return 0;
    }

    • Alex

      When using a character constant with more than one character (e.g. ’45’ or ‘ab’), this is treated as an integer, and the value is implementation-defined (and thus, you shouldn’t do this). Visual Studio 2015 treats ’45’ as integer value 13565, which is then overflowing your char (which has a range of -128 to 127), leaving the value 53, which std::cout is printing as character ‘5’.

  • sehyun

    I have question about std::endl and \n

    you said "std::endl will also ensure that any queued output is actually output before continuing."

    Can you explain more about ‘ensure’ thing?
    Is there any cases that the output does not actually output??

    • Alex

      Yes, if you’re writing output to disk, C++ will often queue up multiple output requests before committing them to disk (for performance reasons). If your program crashes before the output is committed, you’ll lose that output.

  • reznov

    I always struggle with finding a readable table of ASCII characters, never thought of just writing a program for it though. But since it’s so simple here we go, added some repeatability so I don’t have to reboot it 24/7.

    edit: Just noticed how I failed to line out my while function properly, tell your eyes I’m sorry.

  • DeNiSkA

    I found something weird in this code,

    This prints: d   105

    why 105 why not d+5 letters next, that is i?

    I didn’t read any comments on this page, if this question has been already asked my apologize!

  • Nguyen

    Hi Alex,

    As you learned above, chars are always put in single quotes (e.g. ‘a’, ‘+’, ‘5’).

    My silly question is:
    Are "chars" & "characters" the same?

  • Nguyen

    Hi Alex,

    Please help!
    ================================================

    #include <iostream>

    int main()
    {
        std::cout << "Input: ";
        char ch;
        std::cin >> ch;
        std::cout <<"Output_1: "<< ch;

        return 0;
    }
    Here’s the output:
    Input: 65
    Output_1: 6
    ===============================================

    #include <iostream>
    int main()
    {
      //std::cout << "Input: ";
        char ch(65);
      //std::cin >> ch;
        std::cout <<"Output_2: "<< ch;

        return 0;
    }
    Here’s the output:
    Output_2: A
    ============================================================
    Why is the Output_1 different from the Output_2?

    Thanks

    • Nguyen

      Alex,

      I know why Output_1 & Output_2 should be different.  

      I just don’t understand why assigning 65 via cin is different from char ch(65) (direct initialization)?

      Thanks, Have a great day

      • Alex

        It has to do with the way std::cin and std::cout interpret characters.

        When you do char ch(65), you’re saying “assign integer value 65 to ch”. However, if you were to print this value using std::cout, you’d get ‘A’ (because std::cout interprets integers as ASCII characters).

        Similarly, when you read in a value using std::cin, you’re reading in a character value, not an integer value. So when you try to read in “65”, you’re actually only reading in character ‘6’ (which has integer value 54). When you print this back out, you only get ‘6’.

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter