Thread: Converting a string to a character array

  1. #1
    Registered User
    Join Date
    Sep 2002

    Converting a string to a character array

    Hi there,
    I was wondering how you would be able to convert a user-inputted peice of data of type string to a character array. Any ideas?

  2. #2
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    You can get a "const char*" by calling "c_str()" on a string object.


  3. #3
    Registered User
    Join Date
    Sep 2003
    I didn't know that, ha, I would have made a loop to do it --

  4. #4
    carry on JaWiB's Avatar
    Join Date
    Feb 2003
    Seattle, WA
    Better yet, if you don't want a const char* use the copy() function:
    #include <iostream> 
    #include <string>
    using namespace std; 
    int main()
    string s;
    char* buf;
    s = "THIS IS A STRING";
    buf = new char[s.size()+1];
    copy takes two or three parameters:

    copy(char* buf, int len);
    copy(char* buf, int len,int startpos);

    It copies at most len characters into the buffer, and with the second function starts copying with a certain character in the std::string...It doesn't null terminate the char* so take that into account

    Note: You could also simply use data() which works like c_str() (returns an array of chars) but doesnt append a Null character
    "Think not but that I know these things; or think
    I know them not: not therefore am I short
    Of knowing what I ought."
    -John Milton, Paradise Regained (1671)

    "Work hard and it might happen."

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to put a string in a 2 dimensional character array?
    By atif7865 in forum C Programming
    Replies: 2
    Last Post: 12-05-2008, 10:26 PM
  2. OOP Question DB Access Wrapper Classes
    By digioz in forum C# Programming
    Replies: 2
    Last Post: 09-07-2008, 04:30 PM
  3. String Class
    By BKurosawa in forum C++ Programming
    Replies: 117
    Last Post: 08-09-2007, 01:02 AM
  4. Something is wrong with this menu...
    By DarkViper in forum Windows Programming
    Replies: 2
    Last Post: 12-14-2002, 11:06 PM