繁体   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

我是C ++的新手。 我正在尝试将s1内的所有字符更改为“ x”。 但是,当我运行代码时,编译器仅打印了11遍“ hello world”。 为什么会这样呢?

int main(){

    string s1 = "hello world";

    for (auto &c : s1){
        s1[c] = 'x';
        cout << s1 << endl;
    }


    return 0;
}

在您使用的for循环中, c实际上持有字符串s1的不同字符,而不是s1中每个元素的索引。

for (auto &c : s1)

要实际更改字符串的每个字符,请在下面的for循环中使用:

for (int c = 0; c < s1.size(); ++c)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM