C ++ strings, why can not can be used as char arrays?

int main() { string a; a[0] = '1'; a[1] = '2'; a[2] = '\0'; cout << a; } 

Why is this code not working? Why doesn't this print a line?

+7
source share
5 answers

Because a empty. You have the same problem if you try to do the same with an empty array. You should give it some size:

 a.resize(5); // Now a is 5 chars long, and you can set them however you want 

Alternatively, you can set the size when you instantiate a :

 std::string a(5, ' '); // Now there are 5 spaces, and you can use operator[] to overwrite them 
+7
source

Firstly, I think you mean std::string .

Secondly, your line is empty.

Third, if you can use the [] operator to modify an element in a string, you cannot use it to insert an element where it does not exist:

 std::string a = "12"; a[0] = '3'; //a is now "32" a[2] = '4'; //doesn't work 

To do this, you must ensure that your line has allocated enough memory. Therfore

 std::string a = "12"; a[0] = '3'; //a is now "32" a.resize(3); //a is still "32" a[2] = '4'; //a is now "324" 

Fourth, you might want to:

 #include <string> #include <iostream> int main() { std::string a = "12"; std::cout << a; } 
+3
source

Using operator[] to add characters to a string is not supported. There are many reasons why this is so, but one of them:

 string a; a[1] = 12; 

What should a[0] be?

+2
source

In C ++, a string is an object, not an array. Try:

 string a = "12"; cout << a; 

If you like, you can still use the old C-lines, so:

 char a[3]; a[0] = '1'; a[1] = '2'; a[2] = '\0'; ... 

What you are trying to do is mix these two modes, so it doesn't work.

Edit: as others have pointed out, std::string object feeding can work as long as the string has been initialized with sufficient capacity. In this case, the row is empty and, therefore, all indices are outside the bounds.

+1
source

Following the definition for the index operator on std :: string:

 const char& operator[] ( size_t pos ) const; char& operator[] ( size_t pos ); 

Non-constant subscription possible. So the following should work fine:

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

This seems like a cool way to do it though.

+1
source

All Articles