0

I have this code:

string username; string node; string at; string final; struct passwd* user_info = getpwnam("mike"); struct utsname uts; uname(&uts); username = user_info->pw_name; node = uts.nodename; at = "@"; final = username + at +node; i=strlen(final[0]); char *pp = new char[i]; strcpy(pp,final); fputs(pp, stdout); 

I just want to convert these 3 strings in one char*. I know my code is totaly wrong but I test a lot of things through google. Can somebody help me please?

3 Answers 3

3

You simply need to use strings::c_str()

string final; const char *pp = final.c_str(); 

If you need to get the string data in a char* and not const char * then you need to copy it as such:

std::string final; //Allocate pointer large enough to hold the string data + NULL char *pp = new char[final.size() + 1]; //Use Standard lib algorithm to copy string data to allocated buffer std::copy(final.begin(), final.end(), pp); //Null terminate after copying it pp[final.size()] = '\0'; //Make use of the char * //delete the allocated memory after use, notice delete [] delete []pp; 
Sign up to request clarification or add additional context in comments.

Comments

1

Why do you need to have a *char. I would concatonate everything in final. If you need a *char you can acchieve this by calling:

 final.c_str(); 

If you want to use char. Make sure that you reserve enough memory:

 i=final.size()+1; char *pp = new char[i]; 

Comments

1

You can't directly convert a string to a char*.

If a const char* is suitable, you can use string::c_str().

Otherwise, you need to copy the contents of the string to a pre-allocated char array.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.