服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - 带你认识C++中字符型、字符串和转义字符

带你认识C++中字符型、字符串和转义字符

2021-08-01 22:49Python之王小sen C/C++

要在 C++ 中使用字符串,我们首先需要#include 标头,来引入 std::string 的声明,就可以定义std::string类型的变量。

带你认识C++中字符型、字符串和转义字符

字符串

要在 C++ 中使用字符串,我们首先需要#include 标头,来引入 std::string 的声明,就可以定义std::string类型的变量。

就像普通变量一样,可以按照预期对字符串进行初始化或赋值:

  1. // 使用字符串文字“Runsen”初始化myName 
  2. std::string myName{ "Runsen" }; 
  3. // 将字符串文字“maoli”赋给变量myName  
  4. myName = "maoli"; //  

字符串可以使用std::cout打印输出:

  1. #include <iostream> 
  2. #include <string> 
  3.   
  4. int main() 
  5.     std::string myName{ "Runsen" }; 
  6.     std::cout << "My name is: " << myName << '\n'

要将整行输入读入字符串,最好使用该std::getline()函数。std::getline()有两个参数:第一个是std::cin,第二个是你的字符串变量。

  1. #include <string> // For std::string and std::getline 
  2. #include <iostream> 
  3. #include <iomanip> // For std::ws 
  4.   
  5. int main() 
  6.     std::cout << "Enter your full name: "
  7.     std::string name{}; 
  8.     std::getline(std::cin >> std::ws, name); // read a full line of text into name 
  9.   
  10.     std::cout << "Enter your age: "
  11.     std::string age{}; 
  12.     std::getline(std::cin >> std::ws, age); // read a full line of text into age 
  13.   
  14.     std::cout << "Your name is " << name << " and your age is " << age << '\n'
  15.   
  16.     return 0; 

输出如下:

  1. Enter your full name: Runsen 
  2. Enter your age: 22 
  3. Your name is Runsen and your age is 22 

字符

「作用」:字符型变量用于显示单个字符

「语法」:char ch = 'a';

注意1:在显示字符型变量时,用单引号将字符括起来,不要用双引号

注意2:单引号内只能有一个字符,不可以是字符串

  • C和C++中字符型变量只占用1个字节。
  • 字符型变量并不是把字符本身放到内存中存储,而是将对应的ASCII编码放入到存储单元

示例:

  1. int main() { 
  2.   
  3.  char ch = 'a'
  4.  cout << ch << endl; 
  5.  cout << sizeof(char) << endl; 
  6.  
  7.  //ch = "abcde"; //错误,不可以用双引号 
  8.  //ch = 'abcde'; //错误,单引号内只能引用一个字符 
  9.  
  10.  cout << (int)ch << endl;  //查看字符a对应的ASCII码 
  11.  ch = 97; //可以直接用ASCII给字符型变量赋值 
  12.  cout << ch << endl; 
  13.  
  14.  system("pause"); 

ASCII码表格:

带你认识C++中字符型、字符串和转义字符

带你认识C++中字符型、字符串和转义字符

ASCII 码大致由以下「两部分组」成:

  • ASCII 非打印控制字符:ASCII 表上的数字 「0-31」 分配给了控制字符,用于控制像打印机等一些外围设备。
  • ASCII 打印字符:数字 「32-126」 分配给了能在键盘上找到的字符,当查看或打印文档时就会出现。

转义字符

「作用」:用于表示一些不能显示出来的ASCII字符

现阶段我们常用的转义字符有:\n \\ \t

带你认识C++中字符型、字符串和转义字符

示例:

  1. int main() { 
  2.  
  3.  cout << "\\" << endl; 
  4.  cout << "\tHello" << endl; 
  5.  cout << "\n" << endl; 
  6.  
  7.  system("pause"); 

原文链接:https://mp.weixin.qq.com/s/ZJ1TFKxNm4ZDgRyaT9TCjw

延伸 · 阅读

精彩推荐