Search Bar

Thursday, February 16, 2017

2.7 — Chars

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:
CodeSymbolCodeSymbolCodeSymbolCodeSymbol
0NUL (null)32(space)64@96`
1SOH (start of header)33!65A97a
2STX (start of text)3466B98b
3ETX (end of text)35#67C99c
4EOT (end of transmission)36$68D100d
5ENQ (enquiry)37%69E101e
6ACK (acknowledge)38&70F102f
7BEL (bell)3971G103g
8BS (backspace)40(72H104h
9HT (horizontal tab)41)73I105i
10LF (line feed/new line)42*74J106j
11VT (vertical tab)43+75K107k
12FF (form feed / new page)44,76L108l
13CR (carriage return)45-77M109m
14SO (shift out)46.78N110n
15SI (shift in)47/79O111o
16DLE (data link escape)48080P112p
17DC1 (data control 1)49181Q113q
18DC2 (data control 2)50282R114r
19DC3 (data control 3)51383S115s
20DC4 (data control 4)52484T116t
21NAK (negative acknowledge)53585U117u
22SYN (synchronous idle)54686V118v
23ETB (end of transmission block)55787W119w
24CAN (cancel)56888X120x
25EM (end of medium)57989Y121y
26SUB (substitute)58:90Z122z
27ESC (escape)59;91[123{
28FS (file separator)60<92\124|
29GS (group separator)61=93]125}
30RS (record separator)62>94^126~
31US (unit separator)63?95_127DEL (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:
NameSymbolMeaning
Alert\aMakes an alert, such as a beep
Backspace\bMoves the cursor back one space
Formfeed\fMoves the cursor to next logical page
Newline\nMoves cursor to next line
Carriage return\rMoves cursor to beginning of line
Horizontal tab\tPrints a horizontal tab
Vertical tab\vPrints 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 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.

No comments:

Post a Comment

whatiscpp.blogspot.com is a free website devoted to teaching you how to program in C++. Whether you’ve had any prior programming experience or not, the tutorials on this site will walk you through all the steps to write, compile, and debug your C++ programs, all with plenty of examples.