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 an ASCII 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. Instead, it may opt to “collect output” for a while before writing it out. This is done for performance reasons, as in some cases, writing one larger blob of data is much faster than making many small writes.

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: We’re in the process of converting other articles in this tutorial over to ‘\n’ instead of std::endl, because for console output, this is almost always the better choice.)

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.

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.

In the meantime, you should only use ASCII characters when working with characters (and strings). Using characters from other character sets may cause your code to work incorrectly.

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

131 comments to 2.7 — Chars

  • Nguyen

    Hi Alex,

    "A char variable holds a 1-byte integer. However, instead of interpreting the value of the char as an integer (is it a whole number like 1, 2, 3….?), the value of a char variable is typically interpreted as an ASCII character (is it the ASCII Code from 1 to 127?".

    Thanks, Have a great day.

    • Nguyen

      Hi Alex,

      After reading over & over, I have a different understanding about Char.  I guess it should be understood as "A char variable holds a 1-byte integer (a whole number as the value of a char from 0 to 255). However, instead of interpreting the value of the char as an integer (a whole number), the value of a char variable is typically interpreted as an ASCII character (under symbol column)".

      Pleas let me know my assumption is correct.

      Thanks

      • Alex

        This doesn’t seem much different than your previous attempt, except your range here is from 0 to 255 (which is the range of an unsigned char) whereas before you indicated that the top of the range was 127, which would be true for a signed char.

  • Sooi Shanghei

    What’s the difference between "?" and "\?"

    I use "?" in my codes and it works fine.

    • Alex

      Go to http://cpp.sh/ and compile this program:

      The result may be unexpected.

      Some compilers will treat two question marks in a row as a trigraph (three character that are treated as a replacement token for a single character). Using \?\? allows you to explicitly note that you want question marks. Trigraphs are disabled by default in Visual Studio and are deprecated in the C++17 standard.

  • Marius

    Hello, Alex!

    So with this code:

    If I enter the character mu "µ" it tells me the ASCII number is -26.
    I know that mu "µ" is not in the ASCII list, but why does it give me the output of -26?

    Thank you for any response.

    • Alex

      A char can only hold a value between -128 and 127. mu is not an ascii character -- it’s an “extended character” with a code point of greater than 127 (usually 230). Since you’re assigning a character with a code point greater than 127 to a char that can’t hold a value that large, you get overflow. The number “wraps around” into the negative range of the char. When you print it as an int, you’re printing the overflowed value.

    • How did you even enter in the character "mu" in the first place?

  • Kevin ☺

    First of all, Thanks Alex for the website. It really goes in depth compared to some other websites that only teach the syntax and new "words". I also appreciate that you are active and help out anyone that is having trouble. Not only are you helping that person but anyone else who might have the same issue. With that said, I just wanted to showcase a program that I been able to make with what I have learned so far. It might not be the best way to make it but I did my best with what I know so far.

    #include <iostream>
    #include <string>
    #include <iomanip>

    void phase2();
    bool checkforop(std::string operation);
    void calculate(double a, double b, std::string operation);

    void main() {
        phase2();

    }

    void phase2() {
        double a;
        double b;
        std::cin >> a;
        std::cin.ignore();
        std::string operation;
        getline(std::cin, operation);
        if (checkforop(operation)) {
            std::cin >> b;
            calculate(a, b, operation);
        }
        else {
            std::cout << "\aThere was an error with your input. Try again" << std::endl;
            phase2();
        }
    }

    bool checkforop(std::string operation) {
        if (operation == "+") {
            return 1;
        }
        if (operation == "-") {
            return 1;
        }
        if (operation == "*") {
            return 1;
        }
        if (operation == "/") {
            return 1;
        }
        return 0;
    }

    void calculate(double a, double b, std::string operation) {
        std::cout << std::setprecision(9);
        if (operation == "+") {
            std::cout << a << operation << b << "=" << a + b << std::endl;
        }
        if (operation == "-") {
            std::cout << a << operation << b << "=" << a - b << std::endl;
        }
        if (operation == "*") {
            std::cout << a << operation << b << "=" << a * b << std::endl;
        }
        if (operation == "/") {
            std::cout << a << operation << b << "=" << a / b << std::endl;
        }
    }

  • MJ

    Hi Alex - thanks for the tutorials. FYI, you have ads appearing from time to time on your platform (through Ad Choices) that pull the user away from reading the tutorial in order to see the ads, and it makes it difficult to consume your excellent content.

    • Alex

      Next time you encounter this happening, can you take a screenshot and drop me a link via the contact form? I’d like to get to the bottom of this but I can’t reproduce this myself. Thanks!

  • Yannick

    Hi Alex,

    First, I would like to thank you for the outstanding work, thought, and care that went into this tutorial. I wish that I first learned C++ through it rather than taking university courses…

    I have two questions regarding this chapter (if you have the time):

    1) You say in Chapter 2.3 that the C++ specification only guarantees the minimum size of fundamental types, including char (at least 1 byte). However, in this chapter, you say that "char is defined by C++ to always be one byte in size". Is the size fixed or not?

    2) By fooling around and reading other comments, I realized that working with the types char16_t and char32_t is difficult. For one, I can’t figure out if the header <cuchar> is required for them. Also, if I try the following code

    where nb is any number mapped to a Unicode character, then c is printed as an integer rather than a character. Do you know of any resources that could get me (or others) started on these types?

    Thank you again for your time!
    -Yannick

    • Alex

      1) The size of a char is fixed at 1 byte. I’ve updated the prior lesson to note this.
      2) Yes, working with the other char types is difficult. char16_t and char32_t are fundamental types, and should need no header included (just that your compiler is C++11 compliant). However, the iostream library doesn’t support char16_t or char32_t in the way you’d expect, which is part of the reason working with these types is challenging. I’m not aware offhand of any good resources around this, but a google search might turn up some.

  • Jitender Bansal

    Alex sir…
        Feeling very comfortable in learning c++.

    I just need to ask ..char hold 1 byte of memory space means it must represent 256 ASCII characters isn’t but you have mentioned 0-127.
    Confused please clarify.

    • Alex

      A char can hold 256 unique values, but the ASCII character set was only defined to use characters 0-127. This was done so that ASCII values can be used with signed chars, which have a range of -128 to 127.

  • James Ray

    Hi Alex,

    About using wchar_t, I just read this article:
    <a href="https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/">here</a>. Here are some quotes from the end of the article: "In C++ code we just declare strings as wchar_t (“wide char”) instead of char and use the wcs functions instead of the str functions (for example wcscat and wcslen instead of strcat and strlen). To create a literal UCS-2 string in C code you just put an L before it as so: L”Hello”…When CityDesk publishes the web page, it converts it to UTF-8 encoding, which has been well supported by web browsers for many years. That’s the way all 29 language versions of Joel on Software are encoded and I have not yet heard a single person who has had any trouble viewing them."

    • Alex

      That article is from 2003, and is now a bit outdated. At the very least, you should be using char16_t or char32_t instead of wchar_t now.

      The above advice may be fine for creating web pages (since modern browser are capable of rendering UTF-8), but OS consoles have spotty support for UTF-8.

      I could probably write an entire chapter on localization, regionalization, and internationalization. They’re complex subjects. Maybe someday I will.

      • James Ray

        Thanks Alex, I appreciate your feedback.

        • James Ray

          The following comment is [here](https://stackoverflow.com/questions/43322298/what-characters-wont-print-in-c-and-the-command-line-is-there-any-workaround?noredirect=1#comment73798830_43322298): "Alex is mostly right, the article is a bit outdated. It is still incredibly useful as an introduction to encodings and charsets, you just need to be aware that the world is moving forward. Also "OS consoles have spotty support for UTF-8" is not quite true, most modern OSes support it out of the box, with a notable exception of Windows (which you can still coerce into supporting UTF-8, it’s just not the default there.)."

      • MSteven

        what do you mean by localization, regionalization and internationalization?

        • Alex

          https://en.wikipedia.org/wiki/Internationalization_and_localization

          In short, making your code easily adaptable to users who reside in different countries, and may speak different languages, use different date and currency formats, etc…

  • Rohit

    Hi!

    Thanks a lot of making this website, I find it to be a very useful reference.

    I didn’t understand the difference between \n and std::endl.

    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. Instead, it may opt to “collect output” for a while before writing it out. This is done for performance reasons, as in some cases, writing one larger blob of data is much faster than making many small writes.

    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).

    So doesn’t this mean \n buffers and waits to collect output, because std::endl forces the output to be displayed right away?

    Thank you!

  • justin

    The chart in Chapter 1.4c says "static_cast" was not added till C++11, but thats not mentioned in this section. Would it be an issue if some one tried to use it in a non-C++11 compatible compiler?

  • F Zhang

    Does "char" pronounce "Car" (the quad-wheel vehicle) or something else?like prince "char " ming?

    • Alex

      I’ve heard it pronounced in three different ways:
      * Care (as in, I care for you)
      * Car (as in the quad-wheel vehicle)
      * Char (as in the first syllable of charming)

      In almost all cases, Americans tend to favor the very literal pronunciation “Char”. I am uncertain whether that varies in other countries.

    • Zero Cool

      Here in Argentina we pronounce Char like the first syllable of charming.

  • Rafael

    Okay, so I built this small test program where the user must answer two questions. I figured out how to fix it, namely I had to create two seperate "char" types being:

    and

    . My theory is it didn’t work on the below program because "char" can only store one value of user input, like mentioned in this lesson. However, why doesn’t the compiler creates and soon after destroys one of the values after using it like it does with an

    ?

    • Alex

      As you’ve correctly noted, a variable can only hold one value at a time. Your segunda() function overwrites the value set by the primeira() function.

      Part of the problem here is that you’ve defined variable “answer” in the global space (outside of any function), as a global variable. Global variables have different rules than local variables do. I cover them in chapter 4. Until you reach chapter 4, you should only be using local variables, function parameters, and return values.

      primeira() and segunda() should be returning their inputs back to the caller, rather than setting answer.

      • Hey Alex,
        I would like to get your opinion about this very simply code please.
        Thanks

  • micode

    can someone elaborate the use of std::endl here for me?
    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).

    • Alex

      What part of this isn’t clear, so I can better address it? I rewrote the text in the lesson itself to try to make it clearer what the difference between ‘\n’ and std::endl are.

  • Coovi

    I really like this tutorial.
    // ConsoleApplication2.cpp : Defines the entry point for the console application.
    //

    #include "stdafx.h"
    #include <iostream>
    #include <iomanip>
    using namespace std;

    int main()
    {
        char x ;
        cout << "Tap any key you want, and press ENTER" << endl;
        cin >> x;
        cout << "you have enteted :" << x << endl;
        cout << "the charater you entered has a Static NUmber:" << endl;
        cout << static_cast<int>(x) << endl;
        int y;
            y = static_cast<int>(x);
        cout <<y + 1 << endl;
        char z;
        z = y + 1;
            cout << z << endl;
        return 0;
    }

  • 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’.

  • 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?

  • 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!

  • 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.

  • 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.

  • 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’.

  • 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.

  • 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. 🙁

  • 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:

  • Nyap

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

  • Maxwell Pollack

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

  • 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.

  • 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.

Leave a Comment

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