Converting a string to a character array

This is a discussion on Converting a string to a character array within the C++ Programming forums, part of the General Programming Boards category; Hi there, I was wondering how you would be able to convert a user-inputted peice of data of type string ...

  1. #1
    Registered User
    Join Date
    Sep 2002
    Posts
    92

    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
    Posts
    4,699
    You can get a "const char*" by calling "c_str()" on a string object.

    gg

  3. #3
    Registered User
    Join Date
    Sep 2003
    Posts
    13
    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
    Location
    Seattle, WA
    Posts
    1,972
    Better yet, if you don't want a const char* use the copy() function:
    Code:
    #include <iostream> 
    #include <string>
    using namespace std; 
    
    int main()
    {
    string s;
    char* buf;
    s = "THIS IS A STRING";
    buf = new char[s.size()+1];
    s.copy(buf,s.size());
    cout<<buf;
    
    
    }
    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."
    -XSquared

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, 05:30 PM
  3. String Class
    By BKurosawa in forum C++ Programming
    Replies: 117
    Last Post: 08-09-2007, 02: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21