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!
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.)
You can use push_back
to append element as
for(int i=0; i<10; i++){
s2.push_back(s[i]);
}
Or
for(int i=0; i<10; i++){
s2 += s[i];
}
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];
}