Click here to Skip to main content
13,087,941 members (64,348 online)
Rate this:
Please Sign up or sign in to vote.
See more:
Hi All

I want to know that i get in a variable suppose CString testCStr in this variable i get the names of somes step by step

i want to pass this name in an array of character type
     char name[];
   name=testCStr;// at this point it gives me error 

i want to name of CString variable into character type array and use it further operations.

how to transfer the strign in the variable of CString(testCStr). to the char aray variable name;

plz Help
Posted 10-May-12 23:52pm
Updated 11-May-12 10:28am
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

If you really need that (in most cases you don't) then you have to copy the CString content.
(For simplicity I assume you have a ANSI CString, not a wide character one)
const int SIZE = 256;
char name[SIZE];
strncpy(name, testCStr, SIZE-1);
name[SIZE] = '\0';
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

If you're not going to modify the string contents, then you can simply cast the CString to a const pointer.

const char * name = (const char *) testCStr;
Or better,
LPCTSTR name = (LPCTSTR) testCStr;
Rate this: bad
Please Sign up or sign in to vote.

Solution 3

You can use sprintf() function

CString testCStr;
testCStr = "This is an example.";
char * chr = new char[testCStr.GetLength()];
sprintf(chr, "%s", testCStr);
CPallini 17-May-12 3:42am
Do you realize your code is flawed?
(Hint: GetLength does not include the string terminator).
Minor (maybe arguable) points:
- If you suggest using new then it would be nice remembering the OP he/her has to eventually call delete.
- sprintf is overkill for such a task.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web02 | 2.8.170813.1 | Last Updated 17 May 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100