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

练习3.1

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

解答:

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


练习3.2

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

解答:

#include <iostream>
#include <string>

using namespace std;

#define OPT 1

int main(){
	string line, word;
#if OPT==1
	while (getline(cin, line)){}
#else
	while (cin >> word){}
#endif
}

练习3.3

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

解答:

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

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


练习3.4

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

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

解答:

#include <iostream>
#include <string>

using namespace std;

#define OPT 1

int main(){
	string str1, str2;
	cin >> str1 >> str2;
#if OPT==1
	if (str1 != str2){
		str1 > str2? (cout << str1 << endl) : (cout << str2 << endl);
	}
#else
	if (str1.size() != str2.size()){
		str1 > str2 ? (cout << str1 << endl) : (cout << str2 << endl);
	}
#endif
}

练习3.5

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

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

解答:

#include <iostream>
#include <string>

using namespace std;

#define OPT 1

int main(){
	string word, sum;
	while (cin >> word){
#if OPT == 1
		sum += word;
#else
		sum +=  word + " ";
#endif
	}
	cout << sum << endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值