mardi 4 décembre 2018

Why does string size not change if I add an additional character in it?

In the below program, when I add one more character to string, its size still remains the same (as evident from str1.size() function). Why is that?

#include <iostream>
#include <cstring>

using std::cout;
using std::endl;

int main() {

        std::string str1 = "hello";
        cout << "std::string str1 = \"hello\""<< endl;

        cout << "string is " << str1 << " with length " << str1.size() << endl;

        str1[5] = 'a';


        cout << "string is " << str1 << " with length " << str1.size() << endl;

   for (int i = 0 ; i < 7; i++) {
                cout << "str["<<i<<"] = " << str1[i] << " (int)(str[i])" << (int)str1[i] << endl;
        }
}

Output

std::string str1 = "hello"
string is hello with length 5
string is hello with length 5 //expected 6
str[0] = h (int)(str[i])104
str[1] = e (int)(str[i])101
str[2] = l (int)(str[i])108
str[3] = l (int)(str[i])108
str[4] = o (int)(str[i])111
str[5] = a (int)(str[i])97
str[6] =  (int)(str[i])0

Aucun commentaire:

Enregistrer un commentaire