您的位置:首页 > 编程语言 > C语言/C++

《c++ primer》 习题3.7-3.10

2015-05-12 16:46 253 查看
3.7

题目描述:编写一个程序读入两个string对象,测试它们是否相等。若不相等,则指出两个中哪个较大。接着,改写程序测试它们的长度是否相等,若不相等指出哪个较长。

源码解答:

#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::string;

int main()
{
/*test the two strings*/

string s1, s2;
cout << "please input two strings:" << endl;
cin >> s1 >> s2;
if (s1 == s2)
{
cout << "the two strings is equl" << endl;
}
else if (s1>s2)
{
cout << "the first string is bigger" << endl;
}
else
{
cout << "the second string is bigger" << endl;
}
cout << "please input two strings:" << endl;
cin >> s1 >> s2;
if (s1.size() == s2.size())
{
cout << "the length of two strings is equl" << endl;
}
else if (s1.size() < s2.size())
{
cout << "the length of two strings the first < the second" << endl;
}
else
{
cout << "the length of two strings the first > the second" << endl;
}
system("pause");
return 0;
}
题目分析:主要使用了string类类型的size()成员函数和string对象的比较

3.8

题目描述:编写一个程序,从标准输入读取多个string对象,把它们连接起来存放到一个更大的string对象中。并输出连接后的string对象。接着,改写程序,将连接后相邻string对象以空格隔开。

源码解答:

#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::string;

int main()
{
string s;
string s1;
string s2;
while (cin>>s)
{
s1 += s;
s2 = s2 + s+' ';
}
cout << s1<< endl;
cout << s2 << endl;
system("pause");
return 0;
}
题目分析:主要运用了string类型定义的+运算符,注意此运算符返回的是一个string对象。

3.9

题目描述:下列程序实现什么功能?实现合法吗?如果不合法,说明理由。

string s;
cout<<s[0]<<endl;
题目分析:定义了一个string对象,调用默认构造函数,所以s是个空字符串,所以下标运算是不合法的。

3.10

题目描述:编写一个程序,从string对象中去掉标点符号。要求输入到程序的字符串必须包含有标点符号,输出结构则是去掉标点符号后的string对象。

源码解答

#include <iostream>
#include <string>
#include <cctype>

using std::cin;
using std::cout;
using std::endl;
using std::string;

int main()
{
string s;
cin >> s;
string s1;
for (string::size_type index = 0; index != s.size(); ++index)
{
if (!ispunct(s[index]))
{
s1 += s[index];
}
}
cout << s1 << endl;
system("pause");
return 0;
}
题目分析:主要运用字符处理函数ispunct(),注意包含在头文件<cctype>中,尽管缺省,有些编译器不会报错。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: