problem displaying a string .

here is the part of my code

string name;
name[0]='m';
name[1]='a';
name[2]='r';
name[3]='k';
for(int i=0; i<4; i++)
cout<<name[i];

cout<<endl;

however, when i try to display all the name ex:
cout<<name<<end;

it doesn't display it.
why??
How can I fixe the problem?
You're trying to access characters in a string of length 0.

http://www.cplusplus.com/reference/string/string/operator[]/

If pos is less or equal to the string length, the function never throws exceptions (no-throw guarantee).
Otherwise, it causes undefined behavior.
Note that using the reference returned to modify elements that are out of bounds (including the character at pos) also causes undefined behavior.


http://www.cplusplus.com/reference/string/string/at/

Strong guarantee: if an exception is thrown, there are no changes in the string.

If pos is not less than the string length, an out_of_range exception is thrown.


If you try the same code using the member function at() instead of the subscript operator, you'll get this:

terminate called after throwing an instance of 'std::out_of_range'
what():  basic_string::at: __n (which is 0) >= this->size() (which is 0)
Last edited on
hi,
thank you for the answer.
so, how come when i do :
btring name = "mark";
cout<<name;

it display it???

i mean, it is still a string of character for the both cases .
isn't it?

closed account (ybf3AqkS)
Your original code doesn't work because you were not allocating the memory, you were trying to access character elements that did not exist. You could of wrote

1
2
3
4
5
6
7
8
9
 string name;
 name.resize(4);  //provide space for 4 characters
 name[0]='m';
 name[1]='a';
 name[2]='r';
 name[3]='k';

 for(int i=0; i<4; i++)
     cout<<name[i];


When you write string name = "mark"; The constructor is invoked and reserves the memory automatically.
Last edited on
Topic archived. No new replies allowed.