Search code examples
c++arraysstringcharstring-literals

Initializing an array of characters with a string variable


I understand that char a[] = "Hello World"; works, but I was wondering if there was a way that you could have the array of characters initialized by a string inputed at run-time. For example:

string word;

cout << "Enter a word ";

cin >> word;

char a[] = word;

I know that clang++ does not accept this because it says, "array initializer must be an initializer list or string literal".

Is there a work around for this without using pointers?


Solution

  • Use c_str.

    http://en.cppreference.com/w/cpp/string/basic_string/c_str

    And something like this to copy to array:

    strcpy(a, word.c_str());