简体   繁体   English

我正在尝试将s1内的所有字符更改为“ x”。 但是,当我运行代码时,编译器仅打印了11次“ hello world”

[英]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.

相关问题 我正在尝试在 Vscode 上执行此代码,但每当我运行此代码时,它不会获取字符的值,而只是显示一个随机数 - I'm trying to execute this code on Vscode but whenever I'm running this it's not taking the value of character but just showing a random number 为什么在cpp中与'World'进行比较时打印出'Hello'? - why is 'Hello' being printed out when it is compared with 'World' in cpp? 尝试并行化我的代码但是当我运行它时,它永远不会给出正确的输出 - trying to parallelize my code however when I run it, it never gives the correct output 当我试图运行简单的“ Hello World”代码时,Visual Studio 2010崩溃了吗? - Visual Studio 2010 crashes when Im trying to run simple “Hello World” code? 当我尝试运行代码时,在 vscode 中出现奇怪的错误 - Getting an weird error in vscode when i'm trying to run a code 这段代码有什么问题?。 几分钟前我刚刚学习了编程,我正在努力做到这一点 - What's wrong with this code?. I just learned programming a few minutes ago and I'm trying to make this c++。 我试图通过在开关内使用数组来获取用户输入,但是当我运行代码时它显示分段错误? - c++ . I'm trying to get user input by using array inside switch but when i run the code it's showing segmentation fault? 我不了解hello world cocos2d-x的部分代码示例 - I do not understand part of the code example of hello world cocos2d-x 当我在同一范围内多次初始化具有相同名称的局部变量时,为什么C ++ 11编译器不会抱怨? - Why doesn't the C++11 compiler complain when I initialize a local variable with the same name multiple times within the same scope? 如何使用 python 运行 Hello world c++ 代码 - How can I run a Hello world c++ code using python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM