《c++ primer》 习题3.7-3.10
2015-05-12 16:46
253 查看
3.7
题目描述:编写一个程序读入两个string对象,测试它们是否相等。若不相等,则指出两个中哪个较大。接着,改写程序测试它们的长度是否相等,若不相等指出哪个较长。
源码解答:
3.8
题目描述:编写一个程序,从标准输入读取多个string对象,把它们连接起来存放到一个更大的string对象中。并输出连接后的string对象。接着,改写程序,将连接后相邻string对象以空格隔开。
源码解答:
3.9
题目描述:下列程序实现什么功能?实现合法吗?如果不合法,说明理由。
3.10
题目描述:编写一个程序,从string对象中去掉标点符号。要求输入到程序的字符串必须包含有标点符号,输出结构则是去掉标点符号后的string对象。
源码解答
题目描述:编写一个程序读入两个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>中,尽管缺省,有些编译器不会报错。
相关文章推荐
- c++ primer 练习 3.6、3.7、3.8、3.9、3.10、3.11
- C++ Primer第四版习题--3.10
- C++ Primer 习题3.10
- C++ Primer 笔记+习题解答(一)
- C++ Primer 习题8.9 ifstream使用方法
- C++顺序容器删除元素时的一个小陷阱(C++ primer第四版习题9.26)
- c++ primer 习题之 单词转换程序
- 《C++ primer》习题16.1答案
- 《C++ Primer》读书笔记(3.8,3.9,3.10)
- C++ Primer 第五版习题10.32
- c++ primer第五版(中文)习题答案 第二章第四节-const限定符
- 《C++ Primer》第五版课后习题解答_第二章(1)(01-08)
- 《C++ Primer》第五版课后习题解答_第三章(1)(01-05)
- C++ Primer 中文版 第4版 习题4.28
- c++ primer习题6.12答案
- C++ Primer 习题解答 第二章
- C++ primer 习题8-7 9 10
- <C++ Primer_5th>习题_1.4
- <C++ Primer_5th>习题_3.3
- <C++ Primer_5th>习题_3.17