C++ 如何在C++中将字符串转换为char *?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9309961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 12:38:55  来源:igfitidea点击:

How to convert string to char * in C++?

c++visual-c++

提问by Justin k

How can I convert a stringin to char *I was using the following method, but it doesn't work.

我如何将 a 转换stringchar *我使用以下方法,但它不起作用。

At runtime it gives me the following error:

在运行时,它给了我以下错误:

Run-Time Check Failure #3 - The variable 'url' is being used without being initialized.

运行时检查失败 #3 - 变量“url”未初始化就被使用。

eventhough I have initialized it as shown in the code bellow. Can you please show me with an example?

尽管我已经按照下面的代码所示对其进行了初始化。你能给我举个例子吗?

    char* url;
    sup = "news"
    sup="http://www."+sup+"yahoo.com";
    strcpy(url, sup.c_str());

I am using Microsoft Visual Studio 2010, C++ in console

我在控制台中使用 Microsoft Visual Studio 2010、C++

回答by Luchian Grigore

strcpydoesn't allocate memory for you, you must do it yourself, remembering to leave space for the null termination character:

strcpy不会为你分配内存,你必须自己做,记住为空终止符留出空间:

char* url = new char[sup.length()+1];

or

或者

char url[sup.length()+1];
//...
strcpy(url, sup.c_str());

In the first case, don't forget to delete[]the array. The second case will only work if your compiler supports C99 variable-length arrays as an extension.

在第一种情况下,不要忘记delete[]数组。第二种情况只有在您的编译器支持 C99 可变长度数组作为扩展时才有效。

回答by Nitish

In my opinion there are two ways of doing this.

在我看来,有两种方法可以做到这一点。

  1. Using &-operator (ampersand)

    string str = "hello";
    char *p;
    p = &str[0];
    
  2. Using c_str() function

    string s = "hello";
    const char *p; 
    p = s.c_str();
    
  1. 使用 & 运算符(与号)

    string str = "hello";
    char *p;
    p = &str[0];
    
  2. 使用 c_str() 函数

    string s = "hello";
    const char *p; 
    p = s.c_str();
    

I have tested both and they both are working. Kindly correct me if I am wrong.

我已经测试了它们,它们都在工作。如果我错了,请纠正我。

回答by Bojan Komazec

strcpyis unsafe as buffer overflow may occur. Use strncpywhere you're providing exactly number of bytes to copy. You need to allocate memory for the destination buffer and add trailing \0:

strcpy不安全,因为可能会发生缓冲区溢出。strncpy在您提供要复制的确切字节数的地方使用。您需要为目标缓冲区分配内存并添加尾随\0

std::string strInsert("news");
std::string sup("http://www.");
sup += strInsert + "yahoo.com";

char* url = new char[sup.length() + 1];
strncpy(url, sup.c_str(), sup.length());
url[sup.length()] = '
std::vector<char> urlAsVec( sup.begin(), sup.end() );
urlAsVec.push_back( '
std::vector<char> urlAsVec( sup.c_str(), sup.c_str() + sup.size() + 1 );
' ); char * url = &urlAsVec[0]; // pointer you can safely write to
'; // ... use url delete[] url;

回答by CashCow

If you really need a writable buffer of char that is copied from the contents of a std::string, you can use std::vector<char>

如果您确实需要从 std::string 的内容复制的可写字符缓冲区,则可以使用 std::vector<char>

std::vector<char> urlAsVec( sup.size() + 1 );
sup.copy( &urlAsVec[0], sup.size() );

You can also initialize the vector this way:

您还可以通过以下方式初始化向量:

char url[ BUFLEN ] = {0};
sup.copy( url, BUFLEN-1 );

which will write your null-terminator for you too.

这也将为您编写空终止符。

Another alternative:

另一种选择:

char* url = new char[100];

Note that your vector will automatically initialize all its elements to 0 so the null terminator will be there even though sup.copy() doesn't write it. You can use sup.copy( ptr, len)instead of strcpy anyway, which is slightly safer in that you can specify the buffer size (although strncpy would allow that too), although you will still have to write the null terminator manually (or have it already allocated).

请注意,您的向量将自动将其所有元素初始化为 0,因此即使 sup.copy() 没有写入空终止符,它也会在那里。sup.copy( ptr, len)无论如何,您可以使用代替 strcpy ,这稍微安全一些,因为您可以指定缓冲区大小(尽管 strncpy 也允许这样做),尽管您仍然必须手动编写空终止符(或已经分配了它)。

For example if you use this:

例如,如果你使用这个:

url = new char[size];

for some fixed value BUFLEN you will get a copy or partial copy of the source string written into your buffer. Note that my initializer ensures all your unwritten bytes are 0.

对于某些固定值 BUFLEN,您将获得写入缓冲区的源字符串的副本或部分副本。请注意,我的初始化程序确保所有未写入的字节均为 0。

回答by juergen d

std::string sup = "news";
sup="http://www."+sup+"yahoo.com";
char* url = new char[sup.length()+1];
url = const_cast<char*>(sup.c_str());
url[sup.length()] = '##代码##';

std::cout<<url;            //http://www.newsyahoo.com

You have to allocate memory for your char array first.

您必须先为 char 数组分配内存。

回答by atoMerz

Copying from supto urldoesn't mean you have initialized url.
Initializing urlmeans allocating memory for it. Like this:

supto复制url并不意味着您已经初始化了url.
初始化url意味着为其分配内存。像这样:

##代码##

回答by vivek

##代码##

Notice the '\0'at the end of url.

请注意'\0'url 的末尾。