3.1 using声明形式:using namespace::name,例如:using std::cin; using std::cout; 等。头文件代码一般不应适用using声明。
3.2
#include <iostream>
#include <string>
using namespace std;
int main()
{
//读一行
string line;
getline(cin, line);
cout << line << endl;
//读一词
string word;
while (cin >> word)
cout << word << endl;
return 0;
}
3.3 输入运算符忽略字符串开头的空白,从第一个真正字符开始,遇到下一处空白为止;
getline函数遇到换行符位置,会把换行符也读入,但不存储再字符串中。
3.4
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1, str2;
cin >> str1 >> str2;
if (str1 == str2)
cout << "same string" << endl;
else {
if (str1 > str2)
cout << str1 << endl;
else
cout << str2 << endl;
}
if (str1.size() == str2.size())
cout << "same length" << endl;
else {
if (str1.size() > str2.size())
cout << str1 << endl;
else
cout << str2 << endl;
}
return 0;
}
3.5
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
string total;
cin >> total;
while (cin >> str) {
total += " ";
total += str;
}
cout << total << endl;
return 0;
}
3.6
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
cin >> str;
for (auto &c : str)
c = 'X';
cout << str << endl;
return 0;
}
3.7 和使用auto得到相同结果。
3.8 使用while:
int i = 0;
while (s[i] != '\0') {
s[i++] = 'X';
}
使用传统for:
for (int i = 0; i < s.size(); ++i)
s[i] = 'X';
使用范围for循环最好。
3.9 不合法,s为空串,没有s[0]。
3.10
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
cin >> s;
for (auto &c : s) {
if (!ispunct(c))
cout << c;
}
cout << endl;
return 0;
}
3.11 合法,c为常量引用,循环体内不能改变字符值。