[英]I'm trying to change all character within s1 to 'x'. When I run the code, however, the compiler just printed out 'hello world' 11 times
I'm new to C++. 我是C ++的新手。 I'm trying to change all character within s1 to 'x'.
我正在尝试将s1内的所有字符更改为“ x”。 When I run the code, however, the compiler just printed out 'hello world' 11 times.
但是,当我运行代码时,编译器仅打印了11遍“ hello world”。 Why is this happening?
为什么会这样呢?
int main(){
string s1 = "hello world";
for (auto &c : s1){
s1[c] = 'x';
cout << s1 << endl;
}
return 0;
}
In the for loop you are using, c is actually holding different characters of the string s1 not the index of each element in s1. 在您使用的for循环中, c实际上持有字符串s1的不同字符,而不是s1中每个元素的索引。
for (auto &c : s1)
To actually change each characters of the string use below for loop: 要实际更改字符串的每个字符,请在下面的for循环中使用:
for (int c = 0; c < s1.size(); ++c)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.