problems converting string to char[]

This is a discussion on problems converting string to char[] within the C++ Programming forums, part of the General Programming Boards category; Hello! i searched the forum for string to char posts and tried a good one for converting a string to ...

  1. #1
    Registered User
    Join Date
    Oct 2002
    Posts
    30

    problems converting string to char[]

    Hello!

    i searched the forum for string to char posts and tried a good one for converting a string to char[]:

    Code:
    string mystring = "that this and those"; 
    char  mychar[mystring.length()] = "";
    
    for (int i=0; i < mystring.length(); i++)
      mychar[i] = mystring[i];
    
    cout << mychar;
    It gives the right output but appends some weired output and i dont know how to fix it. I also tried to use:

    Code:
    for (int i = 0; i < mystring.length();++i )
    But doesnt work either. There is still this weired appended output.



    Thanks in advance!

    ~Jan

  2. #2
    It's full of stars adrianxw's Avatar
    Join Date
    Aug 2001
    Posts
    4,831
    Set the size of the char array to 1 larger than the CString. You need a NULL on the end to terminate the string. The rubbish you are seeing is whatever happens to be in memory after the end of the characters you are copying.
    Wave upon wave of demented avengers march cheerfully out of obscurity unto the dream.

  3. #3
    Registered User
    Join Date
    Jan 2003
    Posts
    648
    You could always:
    Code:
    string mystring = "that this and those"; 
    char  mychar[mystring.length() + 1];  // allow space for null
    
    strcpy(mychar, mystring.c_str());  // copy the string's data into your c-string

  4. #4
    Registered User
    Join Date
    Jan 2003
    Posts
    648
    Yea, I was being stupid. Just to show, I left two spaces between char and mychar, probably for the * for the new clause. STUPID ME! lol

  5. #5
    Registered User
    Join Date
    Jul 2003
    Posts
    17
    Jan79 wasn't dynamically allocating memory. Jan was using the string class.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 04:45 PM
  2. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 09:33 PM
  3. Another overloading "<<" problem
    By alphaoide in forum C++ Programming
    Replies: 18
    Last Post: 09-30-2003, 10:32 AM
  4. ........ed off at functions
    By Klinerr1 in forum C++ Programming
    Replies: 8
    Last Post: 07-29-2002, 09:37 PM
  5. problems with string manipulation
    By Unregistered in forum C++ Programming
    Replies: 0
    Last Post: 04-24-2002, 04:45 PM

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