您的位置:首页 > 编程语言 > C语言/C++

C++中范围for语句

2016-05-24 21:27 267 查看
如果想对string对象中的每个字符做点什么操作,目前最好的办法是使用C++11新标准提供的一种语句:范围for(range for)语句。

示例代码:

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

int main()
{
string str("some string");
//每行输出str中的一个字符。
for (auto c : str)
cout << c << endl;
return 0;
}


如果想要改变string对象中字符的值,必须把循环变量定义成引用类型。

示例代码:

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

int main()
{
string str("some string");
//转换成大写形式
for (auto &c : str)
c = toupper(c);
cout << str << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: