第三章 3.1节练习 & 3.2.2节练习

来源:互联网 发布:澳洲goat soap知乎 编辑:程序博客网 时间:2024/05/01 19:37

练习3.1

使用恰当的using声明重做1.4.1节(11页)和2.6.2节(67页)的练习。

解答:

这里就不写代码了,因为可以using命名空间或者空间中的对应函数,可以出现很多种组合,可以按照自己喜欢或熟悉的方式来写。


练习3.2

编写一段程序从标准输入中一次读入一整行,然后修改该程序使其一次读入一个词。

解答:

#include <iostream>#include <string>using namespace std;#define OPT 1int main(){string line, word;#if OPT==1while (getline(cin, line)){}#elsewhile (cin >> word){}#endif}

练习3.3

请说明string类的输入运算符和getline函数分别是如何处理空白字符的。

解答:

getline函数处理字符的方式是按换行符来截断标准输入中的字符流的。

而输入运算符是按空格来截断字符流的。


练习3.4

编写一段程序读入两个字符串,比较其是否相等并输出结果。如果不相等,输出较大的那个字符串。

改写上述程序,比较输入的字符串是否登场,如果不等长,输出较大的那个字符串。

解答:

#include <iostream>#include <string>using namespace std;#define OPT 1int main(){string str1, str2;cin >> str1 >> str2;#if OPT==1if (str1 != str2){str1 > str2? (cout << str1 << endl) : (cout << str2 << endl);}#elseif (str1.size() != str2.size()){str1 > str2 ? (cout << str1 << endl) : (cout << str2 << endl);}#endif}

练习3.5

编写一段程序从标准输入中读入多个字符串将它们链接在一起,输出链接成的大字符串。

然后修改上述程序,用空格把输入的多个字符串分隔开来。

解答:

#include <iostream>#include <string>using namespace std;#define OPT 1int main(){string word, sum;while (cin >> word){#if OPT == 1sum += word;#elsesum +=  word + " ";#endif}cout << sum << endl;}


0 0