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;
}
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;
}
Any help would be appreciated!