您的位置:首页 > 其它

使用范围for语句和while循环以及传统for的区别

2016-03-06 11:17 555 查看
首先是使用范围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
!= '\0'){
s
= 'X';
n++;
}

cout << s << endl;

return 0;
}


传统for语句
#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
= 'X';
}
cout << s << endl;

return 0;
}


使用范围for显得更加简明直观。

值得注意的是在范围for中需要用auto来推断字符串中的每一个元素的类型,而且c必须定义为引用类型,否则无法修改字符串的内容。

范围for的语法形式为

for(declaration : expression)

statement

expression是一个序列,如上面代码,她就是一个字符串序列。而declaration部分负责定义一个变量,该变量将用于访问序列终端额基础元素。每一次被迭代,declaration部分的边疆会被初始化为expression部分的下一个元素。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: