C++Primer第五版 3.2.2节练习
来源:互联网 发布:淘宝无法付款怎么回事 编辑:程序博客网 时间:2024/05/19 14:56
练习3.2:编写一段程序从标准输入中一次读入一整行,然后修改该程序使其一次读入一个词。
练习3.3:请说明string类的输入运算符和getline函数分别是如何处理空白字符的。
练习 3.4:编写一段程序读入两个字符串,比较其是否相等并输出结果。如果不相等,输出较大的那个字符串。改写上述程序,比较输入的两个字符串是否等长,如果不等长,输出长度较大的那个字符串。
练习 3.5:编写一段程序从标准输入中读入多个字符串并将它们连接在一起,输出连接成的大字符串。然后修改上述程序,用空格把输入的多个字符串分割开来。
答案:练习3.2 见云盘程序
练习3.3 答:string类的输入运算在读取时会自动忽略开头的空白(即空格符,换行符,制表符),并从第一个真正的字符开始读起,直到遇见下一处空白为止。
getline函数会在最终得到的字符串中保留输入时的空白符,getline只要一遇到换行符就结束读取操作并返回结果,哪怕输入的一开始就是换行符也是如此。如果输入真的一开始就是换行符,那么所得的结果是个空string。
练习3.4 练习3.5见云盘程序
练习3.2
#include <iostream>#include <string>using std::string;using std::cin;using std::cout;using std::endl;int main(){ string line; while (getline(cin,line)) { cout << line << endl; } return 0;}
练习3.2-2
#include <iostream>#include <string>using std::string;using std::cin;using std::cout;using std::endl;int main(){ string word; while (cin >> word) { cout << word << endl; } return 0; }
练习3.4
#include <iostream>#include <string>using std::string;using std::cin;using std::cout;using std::endl;int main(){ string s1, s2; cout << "Please input string s1 and s2:" << endl; while(cin >> s1 >> s2) { if (s1==s2) cout << "String s1 and s2 are same! " << endl; else if(s1 > s2) cout << "String s1 is bigger and s1 is: " << s1 << endl; else cout << "String s2 is bigger and s2 is: " << s2 << endl; } return 0; }
练习3.4-2
#include <iostream>#include <string>using std::string;using std::cin;using std::cout;using std::endl;int main(){ string s1, s2; while (cin >> s1 >> s2) { if (s1.size() == s2.size()) cout << "s1 and s2 have the same size! "<<endl; else if(s1.size() > s2.size()) cout << "The size of s1 is bigger : " << s1 << endl; else cout << "The size of s2 is bigger : " << s2 << endl; } return 0;}
练习3.5
#include <iostream>using std::string;using std::cin;using std::cout;using std::endl;int main(){ string s1, s2; while (cin >> s2) { s1 += s2; } cout << s1 << endl; return 0;}
练习3.5-2
#include <iostream>#include <string>using std::string;using std::cin;using std::cout;using std::endl;int main(){ string s1, s2; while (cin >> s2) s1 += " " + s2; cout << s1 << endl; return 0; }
1 0
- C++Primer第五版 3.2.2节练习
- C++Primer 第五版 1.1节练习
- C++Primer第五版 1.3节练习
- C++Primer第五版 1.6节练习
- C++Primer第五版 2.4节练习
- C++Primer第五版 3.1节练习
- C++Primer第五版 4.2节练习
- C++Primer第五版 4.3节练习
- C++Primer第五版 4.4节练习
- C++Primer第五版 4.6节练习
- C++Primer第五版 4.7节练习
- C++Primer第五版 4.8节练习
- C++Primer第五版 4.9节练习
- C++Primer第五版 4.5节练习
- C++Primer第五版 5.1节练习
- C++Primer第五版 5.2节练习
- C++Primer第五版 6.1节练习
- C++Primer第五版 6.4节练习
- 出差二、三事——北漂18年(25)
- C++Primer第五版 第2章 变量和基本类型(练习解答)
- 解决win10 关键错误开始菜单和cortana无法工作 的问题
- 项目0-宣告“主权”
- C++Primer第五版 3.1节练习
- C++Primer第五版 3.2.2节练习
- ADO.NET封装代码
- C/C++语言中函数参数传递的三种方式
- RS232与RS422/485
- 第2周项目1c/c++语言中函数参数传递的三种方式
- 【第2周 项目2 - 程序的多文件组织】
- 第二周 函数参数的传递
- Paxos算法
- MySQL for Mac 安装和基本操作