首先是使用范围for语句
#include <iostream>
#include <string>
#include <cctype>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main(int argc, char** argv) {
string str;
cout << "请输入一个字符串,可以包括空格: " << endl;
getline(cin, str); //读取一整行 遇到回车符结束
for(auto &c: str) //依次处理字符串中的每一个字符
{
c = 'X';
}
cout << str << endl;
return 0;
}
然后while循环
#include <iostream>
#include <string>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main(int argc, char** argv) {
string s ;
cout << "请输入字符串:" << endl;
//cin >> s;
getline(cin, s); //读取整行,回车符结束
int n = 0;
while(s[n] != '\0'){
s[n] = 'X';
n++;
}
cout << s << endl;
return 0;
}
#include <iostream>
#include <string>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main(int argc, char** argv) {
string s ;
cout << "请输入字符串:" << endl;
//cin >> s;
getline(cin, s); //读取整行,回车符结束
//int n = 0;
for(int n=0; n < s.size();n++)
{
s[n] = 'X';
}
cout << s << endl;
return 0;
}
使用范围for显得更加简明直观。
值得注意的是在范围for中需要用auto来推断字符串中的每一个元素的类型,而且c必须定义为引用类型,否则无法修改字符串的内容。
范围for的语法形式为
for(declaration : expression)
statement
expression是一个序列,如上面代码,她就是一个字符串序列。而declaration部分负责定义一个变量,该变量将用于访问序列终端额基础元素。每一次被迭代,declaration部分的边疆会被初始化为expression部分的下一个元素。