3.6
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1;
getline(cin, s1);//只能用getline这个函数来输入字符串,不能直接用cin,因为cin会遇到空格停止。
if (!s1.empty())
{
for (auto &c : s1)
c = 'x';
cout << s1 << endl;
}
else
cout << "您输入的字符串为空" << endl;
system("pause");
return 0;
}
值得注意的是在输入s1时,不能直接用cin,因为会遇到空格停止,比如:asd fgh 那么得到的s1知识asd而没有空格后面的内容了,getline只会遇到回车才停止。
3.7
传统的for循环:for (decltype(s1.size()) cnt = 0;cnt<s1.size();cnt++) s1[cnt]= 'x';
传统while循环:decltype(s1.size()) cnt = 0;
while (cnt < s1.size())
{
s1[cnt] = 'x';
cnt++;
}
3.10
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1;
getline(cin, s1);
if (!s1.empty())
{
for (auto &c:s1)
if (!ispunct(c))
{
cout << c;
}
cout << endl;
}
else
cout << "您输入的字符串为空" << endl;
system("pause");
return 0;
}