【发布时间】:2020-11-08 05:02:45
【问题描述】:
所以,我是 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;
}
任何帮助将不胜感激!
【问题讨论】:
-
ios::sync_with_stdio(false); cin.tie(0);- 为什么这么多废话? -
@JesperJuhl • (deadpan) 所以程序是高效的。否则会太慢。 (/deadpan)
-
你没有
#include <string>,但是你无缘无故地添加了各种sync_with_stdio的东西.. -
您使用 c-strings 标记了问题,但您的代码中没有任何 c-strings。