
字符串
要在 C++ 中使用字符串,中字字符转义字符我们首先需要#include 标头,符型来引入 std::string 的串和声明,就可以定义std::string类型的中字字符转义字符变量。
就像普通变量一样,符型可以按照预期对字符串进行初始化或赋值:
// 使用字符串文字“Runsen”初始化myName std::string myName{ "Runsen" }; // 将字符串文字“maoli”赋给变量myName myName = "maoli"; // 字符串可以使用std::cout打印输出:
#include <iostream> #include <string> int main() { std::string myName{ "Runsen" }; std::cout << "My name is: " << myName << \n; } 要将整行输入读入字符串,串和最好使用该std::getline()函数。中字字符转义字符std::getline()有两个参数:第一个是符型std::cin,第二个是源码库串和你的字符串变量。
#include <string> // For std::string and std::getline #include <iostream> #include <iomanip> // For std::ws int main() { std::cout << "Enter your full name: "; std::string name{ }; std::getline(std::cin >> std::ws,中字字符转义字符 name); // read a full line of text into name std::cout << "Enter your age: "; std::string age{ }; std::getline(std::cin >> std::ws, age); // read a full line of text into age std::cout << "Your name is " << name << " and your age is " << age << \n; return 0; } 输出如下:
Enter your full name: Runsen Enter your age: 22 Your name is Runsen and your age is 22 字符
「作用」:字符型变量用于显示单个字符
「语法」:char ch = a;
注意1:在显示字符型变量时,用单引号将字符括起来,符型不要用双引号
注意2:单引号内只能有一个字符,串和不可以是中字字符转义字符字符串
C和C++中字符型变量只占用1个字节。 字符型变量并不是符型把字符本身放到内存中存储,而是串和将对应的站群服务器ASCII编码放入到存储单元 示例:
int main() { char ch = a; cout << ch << endl; cout << sizeof(char) << endl; //ch = "abcde"; //错误,不可以用双引号 //ch = abcde; //错误,单引号内只能引用一个字符 cout << (int)ch << endl; //查看字符a对应的ASCII码 ch = 97; //可以直接用ASCII给字符型变量赋值 cout << ch << endl; system("pause"); } ASCII码表格:


ASCII 码大致由以下「两部分组」成:
ASCII 非打印控制字符:ASCII 表上的数字 「0-31」 分配给了控制字符,用于控制像打印机等一些外围设备。 ASCII 打印字符:数字 「32-126」 分配给了能在键盘上找到的字符,当查看或打印文档时就会出现。 转义字符
「作用」:用于表示一些不能显示出来的ASCII字符
现阶段我们常用的亿华云计算转义字符有:\n \\ \t

示例:
int main() { cout << "\\" << endl; cout << "\tHello" << endl; cout << "\n" << endl; system("pause"); }