所以,我是 C++ 的新手,我无法弄清楚为什么会发生这种情况。我有一个包含所有字母的字符串,我将其中的 10 个字符复制到一个新字符串中 s2
, 逐个字符地使用 for 循环如下,当我执行它时 cout
功能是打印一个空行。
#include <iostream>
using namespace std;
int main(){
string s = "abcdefghijklmnopqrstuvwxyz";
string s2;
for(int i=0; i<10; i++){
s2[i] = s[i];
}
cout << s2 << endl;
return 0;
}
但是当我打印这个字符串时 s2
逐个字符我得到了正确的输出#include <iostream>
using namespace std;
int main(){
string s = "abcdefghijklmnopqrstuvwxyz";
string s2;
for(int i=0; i<10; i++){
s2[i] = s[i];
}
for(int i=0; i<10; i++){
cout << s2[i];
}
return 0;
}
任何帮助,将不胜感激!
最佳答案
您的代码都有 undefined behavior . string s2;
刚刚初始化 s2
作为空 std::string
其中不包含任何元素。试图访问元素为 s2[i]
导致UB,意味着一切皆有可能。 (即使它似乎在您的第二个代码片段中提供了正确的输出。)
您可以使用 push_back
将元素附加为
for(int i=0; i<10; i++){
s2.push_back(s[i]);
}
或者for(int i=0; i<10; i++){
s2 += s[i];
}
或者您可以制作 s2
预先包含 10 个元素。string s2(10, '\0'); // or... string s2; s2.resize(10);
for(int i=0; i<10; i++){
s2[i] = s[i];
}
关于c++ - 为什么 cout 不打印这个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62970070/