+ 8
Manav Roy
for(int i = 0; i < 5; i++) {
s2 += s[i];
}
+ 6
Because you are accesing not initialized locations by s2[index] +.
assign value before using it..
s2=s; will done it simply.. why loop?
+ 4
Manav Roy Because a string is immutable. You cannot add or change a string the same way as a normal array, even though a string is a kind of an array.
+ 3
Manav Roy
I think the problem was that s2 wasn't initialised with a string of 5 letters.
Now it seems to work...
If you want it to print "hello",
change "+=" to "=", in order to assign value to the string characters
https://code.sololearn.com/c3nZlDAa1laL/?ref=app
+ 3
Manav Roy
I think it is a memory allocation problem.
s += "a";
works because memory space is reallocated for the string object s. But it does not work for
s[i] = 'a';
if s; (empty string)
Try this: notice the result for s1 and s2.
#include <iostream>
using namespace std;
int main()
{
string s{"world"}, s1{" "}, s2{};
for(int i=0;i<5;i++)
{
s1[i] = s[i];
s2[i] = s[i];
}
cout << "s = " << s << endl;
cout << "s1 = " << s1 << endl;
cout << "s2 = " << s2 << endl;
return 0;
}
+ 3
Manav Roy
I modified your code., By using s2{" "}, s2 now have the memory space for the assignment. Also, using += for char assignment is wrong.
It is basically what ɴᴜʟʟ said. How s2 is initialized matters.
Try this:
#include <iostream>
using namespace std;
int main() {
string s="hello",s2{" "};
int index{};
for(int i=0;i<5;i++)
{
s2[index] = s[i];
index++;
}
cout<<s2;
return 0;
}
+ 3
Bob_Li That must be a special C++ thing to declare a string like that.
I tried some similar in C#, and it didn't work.
By the way, I found out in your example, that if you increase the number of spaces to five, then s2 can contain the entire "hello".
+ 2
First of all your declaration and initialisation is not proper.
Its not concatenating the string,actually it's automatically convert character into unicode or ASCII and add both character,whatever displayed or not is actually equivalent of unicode or ASCII.
Write print statement in for loop with index.
+ 1
Manav Roy
only h is assigned, since s2 is only one char long. You cannot assign the entire s="hello" to s2 using the indexing method.
#include <iostream>
using namespace std;
int main() {
string s="hello",s2{" "};//1 blank char
int index{};
for(int i=0;i<5;i++)
{
s2[index]=s[i];
index++;
}
//only h is assigned.
cout<<s2;
return 0;
}
0
#include <iostream>
using namespace std;
int main() {
string s="hello",s2;
s2=s;
cout<< s2;
return 0;
}
You can do it this way
0
#include <iostream>
using namespace std;
int main() {
string s="hello",s2;
for(int i=0;i<5;i++)
{
s2+=s[i];
}
cout<<s2;
return 0;
}