1

I tried to research this for a bit and I can't figure out the problem

Here's the code:

#include <iostream> #include <stdlib.h> #include <string> void choose(); void newuser(); void admuse(); using namespace std; string x; string z; string w; void CreNeAcc(){ cout << "Enter User Name for your new account\n"; getline(cin, x); cout << "Enter Password for your new account\n"; getline(cin, z); cout << "Would you like the account to be admin?\n"; cout << "Yes = Y, No = N\n"; getline(cin, w); choose(); } void choose(){ if(w == "Y"){ newuser(); admuse(); }else if(w == "N"){ newuser(); }else{ cout << "Invalide Command\n"; } } void newuser(){ const char* Letter_x = x.c_str(); char command [100] = "net user /add "; strcat(command, x); //This is where I get the error strcat(command, " "); strcat(commad, z); system(command); } void admuse(){ system("new localgroup administrators " << x << " /add") } 

also the error its giving me is:

cannot convert 'std::string {aka std::basic_string<char>}' to 'const char*' for argument '2' to 'char* strcat(char*, const char*)'| 
1
  • 2
    You already have the answer in your question... Commented Dec 5, 2013 at 2:04

3 Answers 3

7

You have to use c_str() (see here). It's implemented by simply apending it to your std::string, like so:

string myFavFruit = "Pineapple" const char* foo = myFavFruit.c_str(); strcat(command, foo); 

Actually, you have everything there you're just not using your const char* variable in the strcat()'s arguments. You define Letter_x, but then use x in the function instead. Rewrite your newuser() as follows:

void newuser(){ const char* Letter_x = x.c_str(); char command [100] = "net user /add "; strcat(command, Letter_x); //Here, use 'Letter_x' instead of 'x' strcat(command, " "); strcat(command, z); //You will also need to do your 'c_str()' conversion on z before you can use it here, otherwise you'll have the same error as before. system(command); } 

Lastly, you can avoid all this because you can append strings simply using the += operator (see here). Try this:

string command = "net user /add "; command += x; command += " "; command += z; 
Sign up to request clarification or add additional context in comments.

Comments

5

In order to convert a string into an const char* use c_str().

On a side note tho: why are you using strcat in the first place? You can concatenate strings with the operator+.

string a = "try", b = " this"; string c = a+b; // "try this" 

2 Comments

I think it's c_str(), right?
Of course. I had to somehow not press "_". Thanks for pointing that out!
1

You might be looking for this: How to convert a char* pointer into a C++ string?

According to the link, you may use c_str() to return a pointer to a null terminated char array version of your string.

Comments