String Constants
C/C++ supports one other type of constant: the string. A string is a set of characters
enclosed in double quotes. For example, "this is a test" is a string. You have seen
examples of strings in some of the printf() statements in the sample programs.
Although C allows you to define string constants, it does not formally have a string
data type. (C++ does define a string class, however.)
You must not confuse strings with characters. A single character constant is
enclosed in single quotes, as in 'a'. However, "a" is a string containing only one letter.
Backslash Character Constants
Enclosing character constants in single quotes works for most printing characters. A
few, however, such as the carriage return, are impossible to enter into a string from the
keyboard. For this reason, C/C++ include the special backslash character constants
shown in Table 2-2 so that you may easily enter these special characters as constants.
These are also referred to as escape sequences. You should use the backslash codes
instead of their ASCII equivalents to help ensure portability.
For example, the following program outputs a new line and a tab and then prints
the string This is a test.
#include <stdio.h>
int main(void)
{
printf("\n\tThis is a test.");
return 0;
}
Code Meaning
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\" Double quote
\' Single quote
\0 Null
\\ Backslash
\v Vertical tab
\a Alert
\? Question mark
\N Octal constant (where N is an octal constant)
\xN Hexadecimal constant (where N is a hexadecimalconstant)
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\" Double quote
\' Single quote
\0 Null
\\ Backslash
\v Vertical tab
\a Alert
\? Question mark
\N Octal constant (where N is an octal constant)
\xN Hexadecimal constant (where N is a hexadecimalconstant)
Table 2-2. Backslash Codes
No comments:
Post a Comment