Solved

Converting a string to a character array (char[])

Posted on 2003-11-10
3
374 Views
Last Modified: 2010-04-01
suppose I have

string arg6; //my 6th argument for some function to be called soon

however i have to pass in this argument as a character array, char[]

I tried,

char x[] = arg6.c_str();

but i get some const char* cannot be converted to char[] error...
is there a way to do what I want? I solved my problem by declaring arg6 as a char[] but i still want to know how to convert a string to char[] for my own sake. I do know how to conver it to a char*.

thanks
0
Comment
Question by:lapchern
3 Comments
 
LVL 9

Accepted Solution

by:
tinchos earned 50 total points
ID: 9719754
Hi lapchern,

try with

char x[256];
char *p = x;

strncpy( p, arg6.c_str(), 256 );


Cheers!

Tincho
0
 

Author Comment

by:lapchern
ID: 9719782
cheers!
0
 
LVL 4

Expert Comment

by:skypalae
ID: 9720295
Hi,

The error you mentioned is that compiler cannot convert pointers to arrays (although they are almost the same, it is question of the array size i suppose). So why don't you write your code like this?

string s = "abcd" ;
char *c = (char *) s.c_str () ; // can be 'const char *c = s.c_str ()'

This works ok for me (using VC++ 6.0) ;

S.
0

Featured Post

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

786 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question