Why does this string not print?

1
2
3
4
5
6
7
8
9
10
int main ()
{

string a;
a[0] = 'b';
a[1] ='c';
cout << a;

}

The string and iostream headers are there. Why is it that after changing each 'element' of the string nothing comes out? Printing an individual element (e.g. cout << a[0]; works fine).
The string is empty so you are accessing the characters out of bounds on line 5-6.
+1 peter.

cout will print character up to a.size(). Since a.size() is zero, it will print zero characters.

Accessing outside of your string boundaries is dangerous. You are corrupting the heap. It could possibly crash your program or cause other very strange bugs.

If you want to append character to the end of the string, use the += operator:

1
2
3
4
5
string a;
a += 'b';
a += 'c';

cout << a;
1
2
3
4
5
6
7
8
9
int main ()
{

string a[10];
a[0] = 'a';
a[1] = 'b';
cout << a;

}


Just gives me a memory address.
That's because you're printing a pointer to your array.

1
2
3
4
5
6
7
string a[10];  // this makes 10 strings
a[0] = 'a'; // this assigns the first string to be "a"
a[1] = 'b'; // this assigns the second string to be "b"
cout << a;  // which of the strings are you trying to print?  You are giving it an array, not a string

cout << a[0];  // <- this would print "a" (the first string in your array)
cout << a[1];  // <- this would print "b" (the second string in your array) 

Thanks guys. Sometimes C++ makes me want to learn another language.
Topic archived. No new replies allowed.