简体   繁体   中英

In c++, std::string::size() does not count modified string length

My code is below :

int main(){
    string s = "abcd";
    int length_of_string = s.size();
    cout<<length_of_string<<endl;
    s[length_of_string] = 'e';
    s[length_of_string+1] = 'f';
    int length_of_string2 = s.size();
    cout<<length_of_string2<<endl;
    return 0;
}

As far as I know, every string is terminated with a NULL character. In my code I declare a string with length of 4. Then I print the length_of_string which gives a value of 4. Then I modify it and add two characters, 'e' at index 4 and 'f' at index of 5. Now my string has 6 characters. But when I read its length again it shows me that the length is 4, but my string length is 6.

How does s.size() function is work in this case. Is it not the count until NULL character?

The behaviour of your program is undefined .

The length of a std::string is returned by size() .

Although you are allowed to use [] to modify characters in the string prior to the index size() , you are not allowed to modify characters on or after that.

Reference: http://en.cppreference.com/w/cpp/string/basic_string/operator_at

If you need to push a character at the end of the string you should use std::string::push_back function as:

int main(){
    string s = "abcd";
    int length_of_string = s.size();
    cout<<length_of_string<<endl;
    s.push_back('e');
    s.push_back('f');
    int length_of_string2 = s.size();
    cout<<length_of_string2<<endl;
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM