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

2
  • 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++. Commented Dec 20, 2018 at 3:14
  • Possible duplicate of stackoverflow.com/questions/9438209/… Commented Dec 20, 2018 at 3:21

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

Comments

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.