Md. Mostafizur Rahman
Md. Mostafizur Rahman

Reputation: 481

String assignment confusion

I have the following code.

string s1,s2;
cin>>s1;
s2[0] = s1[0];
cout<<s2.length()<<endl;

The output of s2.length() is zero.

When I print

cout<<s2<<endl;

The output of string s2 is an empty string.

But for

cout<<s2[0]<<endl;

It's print a character.

My question is why is string s2 empty ?

Upvotes: 2

Views: 83

Answers (2)

hamed
hamed

Reputation: 481

"Picaud Vincent" responsed correctly.

The operator[] was builted for accessing index of string or writing to specified index of pre-allocated memory of string. you can't increase size of the string with operator[] .

If you want to Add some chars to end of string you should use operators like += or use push_back() method.

For clarify, += operator or push_back() do these steps sequentially :

1- Check string memory size if there isn't enough space for adding new chars ,they extend string memory

2 - Copy new chars at the end of current string

3 - Increment string length,

But operator[] only set the value of specified index and nothing more, and if you set invalid index, you may receive access violation exception and for sum up operator[] doesn't extend string memory or change string length.

Upvotes: 1

Picaud Vincent
Picaud Vincent

Reputation: 10982

Because operator[i] assumes that 0<=i<size(). If i==size() the behavior is undefined, unless you set s1[0]=std::string::value_type(). See the provided link for further details.

To have some runtime error also note that you can use at() instead of op[]:

#include <string>

int main()
{
  std::string s1;
  s1.at(0) = 'A';
}

gives a runtime error:

terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::at: __n (which is 0) >= this->size() (which is 0)
/bin/bash: line 1: 28559 Aborted                 ./main

Upvotes: 4

Related Questions