Solved

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

Posted on 2003-11-10
3
372 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
Comment Utility
Hi lapchern,

try with

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

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


Cheers!

Tincho
0
 

Author Comment

by:lapchern
Comment Utility
cheers!
0
 
LVL 4

Expert Comment

by:skypalae
Comment Utility
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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

763 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now