int main()
{
string a;
a[0] = '1';
a[1] = '2';
a[2] = '\0';
cout << a;
}
Why doesn't this code work? Why is it not printing the string?
Because a
is empty. You get the same problem if you try to do that same thing with an empty array. You need to give it some size:
a.resize(5); // Now a is 5 chars long, and you can set them however you want
Alternatively, you can set the size when you instantiate a
:
std::string a(5, ' '); // Now there are 5 spaces, and you can use operator[] to overwrite them
First, I think you mean std::string
.
Second, Your string is empty.
Third, while you can use the operator[] to change an element in a string, you cannot use it to insert an element where none exists:
std::string a = "12";
a[0] = '3'; //a is now "32"
a[2] = '4'; //doesn't work
In order to do so, you need to make sure your string has allocated enough memory first. Therfore,
std::string a = "12";
a[0] = '3'; //a is now "32"
a.resize(3); //a is still "32"
a[2] = '4'; //a is now "324"
Fourth, what you probably want is:
#include <string>
#include <iostream>
int main()
{
std::string a = "12";
std::cout << a;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With