简体   繁体   中英

c++ string can't accept new chars if not defined a minimum

I'm aware that the following code

#include <iostream>
#include <string>

int main()
{
std::string s;
s[0] = 'a';
s[1] = 'b';
}

says "string subscript out of range" even though std::string's size is 28 bytes. From previous posts, I read to dynamically make the string bigger as you need. What's the best way to do that? I did the following but it's too ugly.

#include <iostream>
#include <string>

int main()
{
    std::string s;
    char c;
    unsigned x = 0;
    std::cout << "char to append: "; s += " "; // what to do here
    std::cin >> c;
    s[x++] = c; //for future appends, x is already 1 position to the right
    std::cout << s;
    std::cin.get();
    std::cin.get();
}

says "string subscript out of range" even though std::string's size is 28 bytes

No, the logical size of this string is "zero characters".

The bytes making up the container itself are irrelevant.

If you want to add characters, use push_back or the += operator :

s.push_back('a');
s += 'b';

The size of the string object does not indicate the nominal length of the string. Twenty-eight bytes is just the amount of memory that the implementation uses. On a different system it might be more or less.

The way you allocated the string, its length is zero. To expand it, use push_back . You can also initialize it with "ab".

#include <iostream>
#include <string>

int main()
{
    std::string s;
    std::cout << s.length() << '\n';
    s.push_back('a'); // not s[0] = 'a';
    s.push_back ('b'); // not s[1] = 'b';
    std::cout << s.length() << '\n';
    // or initialize it with 'ab'...
    std::string s2 {"ab"};
    std::cout << s2 << std::endl;
}

There are a couple of dozen member-functions of std::string that you should familiarize yourself with. resize() is one of them.

编辑您可能想利用字符串可以以某种方式充当vector<char>的事实,因此在字符串的末尾添加一个字符可以实现为s.push_back(c) ,而删除最后一个字符也可以被实现为s.pop_back()

Resizing a std::string

std::string str;
str.resize(2);
str[0] = 'a';
str[1] = 'b';

The std::string is basically a container of bytes. It has a "length/size" attribute which can be accessed with the length() and size() methods . You can modify this field and ask for a larger memory buffer by calling the resize() method.

Appending to a std::string

If you'd like to append to an std::string , the cleanest way is by using the std::ostringstream , as mentioned in another answer. std::push_back() was also discussed. Another way is by using the std::string 's operator+ and operator+= . Both take a std::string or char.

std::string str;
str += 'a';
str = str + "b";

These methods automatically resize as well as append to the std::string .

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