为什么cout不打印此字符串? [英] why cout is not printing this string?
问题描述
所以,我是C ++的新手,我不知道为什么会这样.我有一个包含所有字母的字符串,我将其中的10个字符复制到了新的字符串 s2
中,并使用如下所示的for循环逐个字符地复制了字符串,并在执行时将 cout
函数正在打印空白行.
So, I'm new to C++ and I can't figure why this is happening. I have a string with all the alphabets and I copied 10 characters from it into a new string s2
, character by character using a for loop as follows and when I execute it the cout
function is printing a blank line.
#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
时,我得到了正确的输出
But when I print this string s2
character by character I got the correct output
#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;
}
任何帮助将不胜感激!
推荐答案
两个代码都具有未定义的行为. string s2;
只是将 s2
初始化为一个空的 std :: string
,其中不包含任何元素.尝试以 s2 [i]
的形式访问元素会导致UB,这意味着一切皆有可能.(即使在您的第二个代码段中似乎也给出了正确的输出.)
Both your code have undefined behavior. string s2;
just initializes s2
as an empty std::string
which contains no elements. Trying to access element as s2[i]
leads to UB, means anything is possible. (Even it appears to give the correct output in your 2nd code snippet.)
您可以使用 push_back
将元素附加为
You can use push_back
to append element as
for(int i=0; i<10; i++){
s2.push_back(s[i]);
}
或
for(int i=0; i<10; i++){
s2 += s[i];
}
或者您可以使 s2
包含10个元素.
Or you can make s2
containing 10 elements in advance.
string s2(10, '\0'); // or... string s2; s2.resize(10);
for(int i=0; i<10; i++){
s2[i] = s[i];
}
这篇关于为什么cout不打印此字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!