Thread: Convert string to char[200]

  1. #1
    Reverse Engineer maxorator's Avatar
    Join Date
    Aug 2005

    Convert string to char[200]

    How can I convert a string to char[200]?

  2. #2
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    New York
    Use the std::string c_str() member, to return a char*. More info:

    You should always check the reference pages.

  3. #3
    Deprecated Dae's Avatar
    Join Date
    Oct 2004
    Heres a post found about it using google, fourth on the list when searching: string to char c++

    The poster gives his version to convert it saying x line isnt working, then at the bottom of the page someone gives the solution line.
    Warning: Have doubt in anything I post.

    GCC 4.5, Boost 1.40, Code::Blocks 8.02, Ubuntu 9.10 010001000110000101100101

  4. #4
    Registered User
    Join Date
    Jan 2005
    Why do you think you need to convert a string to char[200]? There's a good chance you don't.

  5. #5
    Join Date
    Jul 2005
    You you specifically want an array as in char x[200]; to be filled, you can use the std::copy subroutine provided by the <algorithm> header. E.g.

    #include <algorithm>
    #include <string>
    int main() {
        std::string s("Hello!");
        char x[200];
        *(std::copy(s.begin(), s.end() - s.begin() < 200 ? s.end() : s.begin() + 199, x)) = 0;
    This code makes sure that no more than 199 elements are copied, leaving room for the null terminator and assigning it. You should only use c_str() if you intend on only using the returned read-only char* before your next non-const member function on s -- so that makes it only good for short-term use, like functions or methods that expect char*s. You could use strncpy on the c_str, but that's no better than std::copy. In fact, it might be worse because at least one implementation of c_str() that I vaguely remember reading about copies the contents of the string into a separate buffer.
    Last edited by Rashakil Fol; 08-22-2005 at 01:20 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 03-03-2006, 02:11 AM
  2. can anyone see anything wrong with this code
    By occ0708 in forum C++ Programming
    Replies: 6
    Last Post: 12-07-2004, 12:47 PM
  3. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM
  4. ........ed off at functions
    By Klinerr1 in forum C++ Programming
    Replies: 8
    Last Post: 07-29-2002, 09:37 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM