【问题标题】:How to convert std::string to const char in C++ [duplicate]如何在 C++ 中将 std::string 转换为 const char [重复]
【发布时间】:2013-12-21 19:17:29
【问题描述】:

我尝试研究了一下,但我无法找出问题

代码如下:

#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++ string c++11


【解决方案1】:

你必须使用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;

【讨论】:

    【解决方案2】:

    要将string 转换为const char*,请使用c_str()

    附带说明: 你为什么首先使用strcat?您可以使用operator+ 连接字符串。

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

    【讨论】:

    • 我想应该是c_str()吧?
    • 当然。我不得不以某种方式不按“_”。感谢您指出这一点!
    【解决方案3】:

    您可能正在寻找这个:How to convert a char* pointer into a C++ string?

    根据链接,您可以使用c_str() 来返回指向字符串的空终止字符数组版本的指针。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-11
      • 2014-07-13
      • 1970-01-01
      • 1970-01-01
      • 2014-03-17
      • 2016-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多