gpt4 book ai didi

c++ - 字符串大小不需要的输出

转载 作者:行者123 更新时间:2023-11-30 01:27:21 26 4
gpt4 key购买 nike

我无法在这一小段代码中找到错误。有什么问题吗?

string f,s;
f[0] = 'd';
s.append(f);
cout<<f.length()<<" "<<f<<" "<<f[0]<<endl;
cout<<s.length()<<" "<<s<<" "<<s[0]<<endl;
Output is :
0 d
0 d

即使我将 s.length 更改为 s.size,结果也是一样的。为什么 s[0] = 'd's.size() = 0;

最佳答案

当您创建它们时,这两个字符串都是空的,它们不包含任何字符。 f[0] 越界,访问空容器的任何元素都是未定义的行为,因此任何事情都可能合法发生。

你需要做的

string f(1, 'd'), s; // creates f with 1 repetition of 'd'
s.append(f);
...

或者

string f, s;
f += 'd'; // or f.push_back('d'), or f.append('d'), or...
s.append(f);
...

关于c++ - 字符串大小不需要的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9091337/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com