Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ strings why cant be used as char arrays?

Tags:

c++

int main()
{    
    string a;

    a[0] = '1';
    a[1] = '2';
    a[2] = '\0';

    cout << a;
}

Why doesn't this code work? Why is it not printing the string?

like image 412
user1896457 Avatar asked Dec 12 '12 02:12

user1896457


2 Answers

Because a is empty. You get the same problem if you try to do that same thing with an empty array. You need to 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
like image 193
Cornstalks Avatar answered Oct 12 '22 13:10

Cornstalks


First, I think you mean std::string.

Second, Your string is empty.

Third, while you can use the operator[] to change an element in a string, you cannot use it to insert an element where none exists:

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

In order to do so, you need to make sure your string has allocated enough memory first. 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, what you probably want is:

#include <string>
#include <iostream>
int main()
{    
    std::string a = "12";    
    std::cout << a;
}
like image 29
Carl Avatar answered Oct 12 '22 13:10

Carl