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

首先是使用范围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;
}


传统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[n] = 'X';
	  }  
	cout << s << endl;
	 
	return 0;
}

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

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

范围for的语法形式为

for(declaration : expression)
statement


expression是一个序列,如上面代码,她就是一个字符串序列。而declaration部分负责定义一个变量,该变量将用于访问序列终端额基础元素。每一次被迭代,declaration部分的边疆会被初始化为expression部分的下一个元素。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值