问题:
constr char *title 是把test中"s1 <= \"ABC"\"的地址作为参数传给title?
字符串常量
- 例:“program”
- 各字符连续、顺序存放、每个字符占一个字节,以‘\0’结尾,相当于一个隐含创建的字符常量数组
- “program”出现在表达式中,表示这一char数组的首地址
- 首地址可以赋给char常量指针
const char *STRING1 = "program";
用字符数组存储字符串(C风格字符串)
string类
- 使用字符串类string表示字符串
- string实际上是对字符数组操作的封装
string类常用的构造函数
- string(); //默认构造函数,建立一个长度为0的串 例: string s1;
- string(const char *s); //用指针s所指向的字符串常量初始化string对象 例: string s2 = “abc”;
- string(const string& rhs); //复制构造函数 例: string s3 = s2;
//例 6-23 string 类应用举例
#include <string>
#include <iostream>
using namespace std;
//根据value的值输出true或false
//title为提示文字
inline void test(const char *title, bool value)//inline把函数指定为内联函数.解决一些频繁调用的函数大量消耗栈空间(栈内存)的问题
{
cout << title << " returns " << (value ? "true" : "false") << endl;
}
int main() {
string s1 = "DEF";
cout << "s1 is " << s1 << endl;
string s2;
cout << "Please enter s2: ";
cin >> s2;
cout << "length of s2: " << s2.length() << endl;
//比较运算符的测试
test("s1 <= \"ABC\"", s1 <= "ABC");
test("\"DEF\" <= s1", "DEF" <= s1);
//连接运算符的测试
s2 += s1;
cout << "s2 = s2 + s1: " << s2 << endl;
cout << "length of s2: " << s2.length() << endl;
return 0;
}
考虑:如何输入整行字符串?
- 用cin的>>操作符输入字符串,会以空格作为分隔符,空格后的内容会在下一回输入时被读取
输入整行字符串
- getline可以输入整行字符串(要包string头文件),例如: getline(cin, s2);
- 输入字符串时,可以使用其它分隔符作为字符串结束的标志(例如逗号、分号), 将分隔符作为getline的第3个参数即可, 例如: getline(cin, s2, ',');
#include <string>
#include <iostream>
using namespace std;
int main() {
for(int i = 0; i < 2;i++){
string city,state;
getline(cin,city,',');
getline(cin,state);
cout << "City: " << city << "State: " << state << endl;
}
return 0;
}