C++Primer Fifth Edition: Exercise 3.6 3.7 3.8 3.9 3.10 3.11

Exercise 3.6

int main()
{
    
    
	string s = "Hello world!";

	for (auto& c : s)
		c = 'X';
	cout << s << endl;
}

Exercise 3.7

The auto keyword type is char, and the result remains unchanged

Exercise 3.8

int main()
{
    
    
	string s = "Hello world!";

	for (string::size_type i = 0; i != s.size(); ++i)
		s[i] = 'X';

	string::size_type i = 0;
	while (i != s.size())
		s[i++] = 'X';
}

I think the for loop is better, more intuitive and convenient

Exercise 3.9
is illegal, string is initialized as an empty string by default, and the subscript is out of range

Exercise 3.10

#include<iostream>
#include<cctype>
using namespace std;

int main()
{
    
    
	string s = "Hello world!";

	for (auto& c : s)
		if (ispunct(c))
			c = ' ';
	cout << s << endl;
}

Exercise 3.11 is
legal, the type of c is char&
can be accessed but the value cannot be changed

Guess you like

Origin blog.csdn.net/Xgggcalled/article/details/109009060