2.7 chars

from http://www.learncpp.com/cpp-tutorial/27-chars/

尽管char类型是一个整数,相比于整数,我们通常用另一种方式对char进行处理。字符能够存储一些小的数,或是ASCII字符集里的字符。ASCII表示American Standard Code for Information Interchange,它给出了美国标准的键盘与1到127数字之间的关系图。举例,'a'在关系图中的代号为97,'b'98。字符总是放在单引号里。

   1: char chValue = 'a';
   2: char chValue2 = 97;

上面两个式子是等同的。

cout输出的是字符而不是整数。

   1: char chChar = 97; // assign char with ASCII code 97
   2: cout << chChar; // will output 'a'

如果我们想要输出整数,我们可以使用强制转换的方式实现。

   1: char chChar = 97;
   2: cout << (int)chChar; // will output 97, not 'a'

 

 

看一下下面的例子,输入字符,并没别以数字和字符的形式输出:

   1: #include "iostream";
   2:  
   3: int main()
   4: {
   5:     using namespace std;
   6:     char chChar;
   7:     cout << "Input a keyboard character: ";
   8:     cin >> chChar;
   9:     cout << chChar << " has ASCII code " << (int)chChar << endl;
  10: }

 

注意:

   1: char chValue = '5'; // assigns 53 (ASCII code for '5')
   2: char chValue2 = 5; // assigns 5

 

转义字符(Escape sequences)

一些字符有特殊的意义,可用加\的转义字符实现。

最常用的是换行符。

   1: #include <iostream>
   2:  
   3: int main()
   4: {
   5:     using namespace std;
   6:     cout << "First line\nSecond line" << endl;
   7:     return 0;
   8: }

 

输出:

First line
Second line

另一个是制表符:

   1: #include <iostream>
   2:  
   3: int main()
   4: {
   5:     using namespace std;
   6:     cout << "First part\tSecond part";
   7: }

输出:

First part        Second part

其他的一些如:

\',\",\\

NameSymbolMeaning
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/hex number \(number) Translates into char represented by octal/hex number
posted @ 2012-05-07 10:55  grassofsky  阅读(282)  评论(0编辑  收藏  举报