C++ Primer(第五版)3.1--3.2.3节练习

本文详细解析了C++ Primer第五版第3.1至3.2.3节的练习内容,涵盖了using声明的使用、输入运算符的行为以及getline函数的工作原理。同时,探讨了不同类型的循环结构,包括while、传统for和范围for循环的适用场景,并讨论了C++中的常量引用在循环中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

3.1    using声明形式:using namespace::name,例如:using std::cin; using std::cout; 等。头文件代码一般不应适用using声明。

3.2    

#include <iostream>
#include <string>

using namespace std;

int main()
{
//读一行
	string line;
	getline(cin, line);
	cout << line << endl;
//读一词
	string word;
	while (cin >> word)
		cout << word << endl;
	return 0;
}

3.3    输入运算符忽略字符串开头的空白,从第一个真正字符开始,遇到下一处空白为止;
         getline函数遇到换行符位置,会把换行符也读入,但不存储再字符串中。

3.4    

#include <iostream>
#include <string>

using namespace std;

int main()
{
	string str1, str2;

	cin >> str1 >> str2;
	if (str1 == str2)
		cout << "same string" << endl;
	else {
		if (str1 > str2)
			cout << str1 << endl;
		else
			cout << str2 << endl;
	}

	if (str1.size() == str2.size())
		cout << "same length" << endl;
	else {
		if (str1.size() > str2.size())
			cout << str1 << endl;
		else 
			cout << str2 << endl;
	}

	return 0;
}

3.5    

#include <iostream>
#include <string>

using namespace std;

int main()
{
	string str;
	string total;
	cin >> total;
	while (cin >> str) {
		total += " ";
		total += str;
	}

	cout << total << endl;

	return 0;
}

3.6    

#include <iostream>
#include <string>

using namespace std;

int main()
{
	string str;
	cin >> str;
	for (auto &c : str)
		c = 'X';
	cout << str << endl;
	return 0;
}

3.7    和使用auto得到相同结果。

3.8    使用while:

int i = 0;
while (s[i] != '\0') {
    s[i++] = 'X';
}

         使用传统for:

for (int i = 0; i < s.size(); ++i)
    s[i] = 'X';

         使用范围for循环最好。

3.9    不合法,s为空串,没有s[0]。

3.10    

#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s;
	cin >> s;
	for (auto &c : s) {
		if (!ispunct(c))
			cout << c;
	}
	cout << endl;
	return 0;
}

3.11    合法,c为常量引用,循环体内不能改变字符值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值