lundi 3 avril 2017

Storing std::string as character array

I'm trying to convert an std::string into a c string (my real problem is closer to this; I'm trying a workaround).

  1. How does one store an std::string as a character array?
  2. Why do std::string.data() and std::string.c_str() return char [(<anonymous> + 1)] instead of the expected const char*? Or do I have these mixed up, and if so, how do I work with these types?

    #include <string>
    #include <iostream>
    
    int main()
    {
      std::string sstring = "I'm an std string!";
    
      char cstring[sstring.size()];
    
      cstring = sstring.c_str();
      std::cout << std::string(sstring.c_str());
    
      return 0;
    }
    
    

Compilation results in

scratch.cpp:10:11: error: incompatible types in assignment of ‘const char*’ to ‘char [(<anonymous> + 1)]’

I wasn't able to find a relevant, preexisting question.

Aucun commentaire:

Enregistrer un commentaire