Constructing std::string like an array
I want to construct a std::stri开发者_运维问答ng object like an array:
std::string str("");
str[0] = 'A';
str[1] = 'b';
str[2] = 'h';
str[3] = 'i';
str[4] = '\0';
std::cout<<str;
But it doesnt print the string. What am i missing?
Firstly, std::string is not a C-string. You do not need to NULL-terminate it. Secondly, the [] operator is only valid for indices which are < std::string::length(), meaning that at least N elements must be allocated in advance before you can access an element between 0 and N-1.
std::string str(4); // construct a string of size 4
str[0] = 'A';
str[1] = 'b';
str[2] = 'h';
str[3] = 'i';
std::cout << str;
Edit: But also see Johnsyweb's answer. The big advantage of std::string over C-strings is that you don't have to worry about memory allocation. You can use the += operator or push_back member function, and can build the string character-by-character without worrying about how much memory to reserve.
Try
std::string (4, ' ');
instead of
std::string("");
basic_string's operator[] returns a reference to the specified character, but since your string is empty, it contains no characters.
What am i missing?
You are missing the whole point of using a std::string. That approach may work for arrays of char, but not for strings.
Consider std::string::operator += instead.
You allocated the string to be "", that is, exactly 0 bytes long.
You are then trying to write chars outside of bounds of the string - which doesn't work.
you should create a space in the memory for your array
using namespace std;
char str[5];
str[0] = 'A';
str[1] = 'b';
str[2] = 'h';
str[3] = 'i';
str[4] = '\0';
cout << str ;
加载中,请稍侯......
精彩评论