1

I'm trying to split a string into an array of individual characters. However, I would like the string to be input by the user, for which I need to define the string using a variable.

My question is, why does this work:

#include <iostream>
using namespace std;
int main() {
char arr [] = {"Giraffe"};
cout << arr[0];
    return 0;
}

But this doesn't?

#include <iostream>
using namespace std;
int main() {
string word;
word = "Giraffe";
char arr [] = {word};
cout << arr[0];
    return 0;
}

Thanks

Faero
  • 21
  • 3
  • Because a `std::string` does not have an automatic conversion to a plain `char` array. That's how C++ works (or doesn't work, depending on one's frame of reference). Not even mentioning that variable-length arrays are not standard C++. – Sam Varshavchik Dec 20 '18 at 03:14
  • Possible duplicate of https://stackoverflow.com/questions/9438209/for-every-character-in-string – Tyzoid Dec 20 '18 at 03:21

2 Answers2

1

Your example doesn't work because you're trying to put a std::string into an array of char. The compiler will complain here because std::string has no type conversion to char.

Since you're just trying to print the first character of the string, just use the array accessor overload of std::string, std::string::operator[] instead:

std::string word;
word = "Giraffe";
std::cout << word[0] << std::endl;
Tyzoid
  • 1,072
  • 13
  • 31
0

In your second example, the type of word is a std::string and there are no default type conversions from std::string to the type char.

On the other hand, the first example works because it can be interpreted as an array of char (but actually its just c-style const char *).

If, for some reason, you would want to convert std::string into the c-style char array, you might want to try something like this...

#include <iostream>
#include <string>
#include <cstring>

int main(void) 
{
    std::string word;
    word = "Giraffe";
    char* arr = new char[word.length() + 1];     // accounting for the null-terminating character
    strcpy(arr, word.data());
    std::cout << arr[0] << std::endl;
    delete[] arr;                                // deallocating our heap memory
    return 0;
}
K. Kiryu
  • 59
  • 3