C++字符串
C风格字符串,以空字符(null character
)结尾,空字符被写为\0
,其ASCII码为0
char dog[8] = {'b', 'e', 'a', 'u', 'x', ' ', 'I', 'I'}; // not a string
char cat[8] = {'f', 'a', 't', 'e', 's', 's', 'a', '\0'}; // is a string
注意:C++很多字符串处理函数,都逐个地处理字符串中的字符,直到到达空字符为止
字符串常量(字符串字面量)
字符串常量(字符串字面量),使用双引号括起字符串即可
char bird[11] = "Mr. Cheeps";
char fish[] = "Bubbles";
用引号括起的字符串隐式地包括结尾的空字符。另外,各种C++输入工具通过键盘输入,将字符串读入到char
数组中时,将自动在结尾加上空字符
因确保数组足够大,能够存储字符串作用所有字符,包括空字符
字符串常量 vs 字符常量
字符串常量使用双引号,字符常量使用单引号
拼接字符串常量
第一个字符串中的\0
字符将被第二个字符串的第一个字符取代
cout << "ABCD" " EFG" << endl;
字符串输入
cin
使用空白(空格、制表符和换行符)来确定字符串的结束位置
如下的例子:
#include <iostream>
int main()
{
using namespace std;
const int ArSize = 20;
char name[ArSize];
char dessert[ArSize];
cout << "Enter your name:\n";
cin >> name;
cout << "Enter your favorite dessert:\n";
cin >> dessert;
cout << "I have some delicious " << dessert;
cout << " for you, " << name << ".\n";
return 0;
}
当输入name
为steven jobs
时,cout
输出结果为:
I have some delicious jobs for you, steven.
可见,这里只是将name
赋值为steven
,而dessert
则赋值为jobs
如何解决这个问题呢?
采用面向行而不是面向单词的的方法,如getline()
和 get()
区别:getline()
将丢弃换行符,而get()
则将换行符保留在输入序列中
getline()方法
getline()
函数读取整行,它通过回车键输入的换行符来确定输入结尾
getline()
函数在读取指定数目的字符或遇到换行符时停止读取
如:
cin.getline(name, 19);
表示,使用getline
将一行读入到name
数组中,字符不超过19个(最多18个字符,余下的空间用于存储自动在结尾处添加的空字符)。
修改上面的代码:
cout << "Enter your name:\n";
cin.getline(name, ArSize);
cout << "Enter your favorite dessert:\n";
cin.getline(dessert, ArSize);
get()方法
get()
方法不丢弃换行符,而是将其留在输入队列中。如果连续两次调用get()
cout << "Enter your name:\n";
cin.get(name, ArSize);
cout << "Enter your favorite dessert:\n";
cin.get(dessert, ArSize);
第一次调用后,换行符将留在输入队列中,因此第二次调用时看到的第一个字符就是换行符。
可使用cin.get()
读取下一个字符(即使是换行符)
cout << "Enter your name:\n";
cin.get(name, ArSize);
cin.get();
cout << "Enter your favorite dessert:\n";
cin.get(dessert, ArSize);
另一种形式是将函数拼接起来:
cin.get(name, ArSize).get();