c++ - 如何在 C++ 中将 std::string 转换为 const char

标签 c++ string c++11

<分区>

我试着研究了一下,但我无法找出问题所在

代码如下:

#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")
}

它给我的错误也是:

cannot convert 'std::string {aka std::basic_string<char>}' to 'const char*' for argument '2' to 'char* strcat(char*, const char*)'|

最佳答案

您必须使用 c_str()(参见 here)。它通过简单地将其附加到您的 std::string 来实现,如下所示:

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

实际上,您拥有一切,只是没有在 strcat() 的参数中使用您的 const char* 变量。您定义了 Letter_x,但随后在函数中使用了 x。重写你的 newuser() 如下:

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);
}

最后,您可以避免这一切,因为您可以简单地使用 += 运算符附加字符串(参见 here )。试试这个:

string command = "net user /add ";
command += x;
command += " ";
command += z;

关于c++ - 如何在 C++ 中将 std::string 转换为 const char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20390008/

相关文章:

C++ 与 Crow、CMake 和 Docker

sql-server - 使用 SQL : How to extract a record within a JSON object? 解析 JSON

c++ - 我可以使用 std::generate 来获取 std::array<T, 2> 的 vector 吗?

c++11 - 将 std::vector 扩展到参数包中

java - 将 C++ OpenGL 转换为 Java/LWJGL

c++ - 从函数返回时 std::pair second 的奇怪行为

c++ - 使用模板化可变模板参数作为专用参数

javascript - 如何解析 key :value pair on JSON-like string with RegEx on JavaScript?

string - 除了做 I/O 之外,我应该总是使用 rune 而不是字符串吗

c++ - C++ 标准库是 C++ 语言的一部分吗?