Converting String to Cstring in C++

后端 未结 3 1335
南旧
南旧 2020-12-24 14:53

I have a string to convert, string = \"apple\" and want to put that into a C string of this style, char *c, that holds {a, p, p, l, e, \'\\0\

相关标签:
3条回答
  • 2020-12-24 15:11

    .c_str() returns a const char*. If you need a mutable version, you will need to produce a copy yourself.

    0 讨论(0)
  • vector<char> toVector( const std::string& s ) {
      string s = "apple";  
      vector<char> v(s.size()+1);
      memcpy( &v.front(), s.c_str(), s.size() + 1 );
      return v;
    }
    vector<char> v = toVector(std::string("apple"));
    
    // what you were looking for (mutable)
    char* c = v.data();
    

    .c_str() works for immutable. The vector will manage the memory for you.

    0 讨论(0)
  • 2020-12-24 15:17
    string name;
    char *c_string;
    
    getline(cin, name);
    
    c_string = new char[name.length()];
    
    for (int index = 0; index < name.length(); index++){
        c_string[index] = name[index];
    }
    c_string[name.length()] = '\0';//add the null terminator at the end of
                                  // the char array
    

    I know this is not the predefined method but thought it may be useful to someone nevertheless.

    0 讨论(0)
提交回复
热议问题