How to convert std::string to const char in C++
本问题已经有最佳答案,请猛点这里访问。
我试着研究一下这个问题,但没能找出问题所在。
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | #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 "; getline(cin, x); cout <<"Enter Password for your new account "; getline(cin, z); cout <<"Would you like the account to be admin? "; cout <<"Yes = Y, No = N "; getline(cin, w); choose(); } void choose(){ if(w =="Y"){ newuser(); admuse(); }else if(w =="N"){ newuser(); }else{ cout <<"Invalide Command "; } } 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") } |
它给我的错误是:
1 | cannot convert 'std::string {aka std::basic_string<char>}' to 'const char*' for argument '2' to 'char* strcat(char*, const char*)'| |
你必须使用
1 2 3 | string myFavFruit ="Pineapple" const char* foo = myFavFruit.c_str(); strcat(command, foo); |
实际上,你已经拥有了一切,你只是没有在
1 2 3 4 5 6 7 8 9 | 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); } |
最后,您可以避免所有这一切,因为您只需使用
1 2 3 4 | string command ="net user /add"; command += x; command +=""; command += z; |
为了将
旁注tho:你为什么一开始使用
1 2 | string a ="try", b =" this"; string c = a+b; //"try this" |
您可能正在寻找:如何将char *指针转换成C++字符串?
根据链接,您可以使用