C++ 字符串可以转换为固定大小的字符数组吗?

问题描述 投票:0回答:8

嗨,我有以下代码:

char msg[10000];
string mystr = "hello";

我想将 mystr 放入 msg 中。有没有办法做到这一点?我尝试了各种方法,但还是不行:

incompatible types in assignment of 'const char*' to char [10000]'

我尝试过:

msg = mystr.c_str();

msg = (char[10000])mystr;

无济于事。

c++ string std cstring
8个回答
5
投票

您可以尝试

std::copy
。比如:

std::copy(mystr.begin(), mystr.end(), msg);

我会避免使用 C++ 中的

C
字符串函数,例如
mempcy
strcpy


2
投票

看一下 string::copy - 它需要一个字符串并将其放入数组中。

在你的情况下是:

std::size_t length = mystr.copy(msg,10000);
msg[length]='\0';

0
投票

C 中的字符串赋值是不同的。您必须将字节复制到目标字符串中。

memcpy_s(msg, 1000, mystr.c_str(), mystr.length()) // safe windows version

memcpy(msg, mystr.c_str(), mystr.length()) // unix version


0
投票
char msg[10000];
string mystr = "hello";

strcpy(msg, mystr.c_str());
cout<<msg;

0
投票

使用 std::string: 的复制成员函数

size_t len = mystr.copy(msg, (sizeof msg)-1);
msg[len] = 0;

0
投票

编译器有时会为数组类型生成奇怪的错误消息。

这里将以前的答案汇总到一个粘贴和编译程序中。

#include <string>
#include <iostream>

#if 1

int main(int argc, char **argv)
{
    using std::cout;
    using std::endl;

    char msg[1000] = {0};    // initialize to 0 here since we're printing below
                            // the <type> <array-name>[<size>] = {0} just fills a POD struct or an array with 0s

    std::string mystr = "hello";

    // if, at some point, you have things changing "mystr"
    // you'll need to make sure that it will fit in msg[]

    cout << "Before strcpy: \"" << msg << "\"" << endl;

    // I'll just finish the statement in mystr...
    mystr += " world!";

    if(mystr.length() < sizeof(msg)){
        strcpy(
            msg,            // <- put in here until we find a '\0'
            mystr.c_str()    // <- take from here (which could be a temporary buffer)
            );
    }

    //MSC will complain about strcpy being unsafe
    //
    // you can use the below instead (if you really feel the need to), which is
    // the MS-specific equivalent to the above.
    /*
        strcpy_s(
            msg,            // <- put in here until we find a '\0' or the size limit is reached
            sizeof(msg),    // <- don't put any more than this many chars in msg
            mystr.c_str()    // <- take from here
            );
    */

    cout << "After strcpy: \"" << msg << "\"" << endl;

    return 0;
}

#else

// Similarly, using wchar_t (a usually non-byte-sized character type)
//
// note where the divisions occurr

int main(int argc, char **argv)
{
    using std::wcout;
    using std::endl;

    wchar_t msg[1000] = {0};
    std::wstring mystr = L"hello";

    wcout << "Before strcpy: \"" << msg << "\"" << endl;

    mystr += L" world";

    if(mystr.length() < (sizeof(msg)/sizeof(wchar_t))){
        // mystr wil fit!
        wcscpy(
            msg,            // <- put in here until we find a '\0'
            mystr.c_str()    // <- take from here (which could be a temporary buffer)
            );
    }

    // Similar to the char case in the first preprocessor block
    /*
        wcscpy_s(
            msg,                            // <- put in here until we find a '\0' or the size limit is reached
            sizeof(msg)/sizeof(wchar_t),    // <- don't put any more than this many wchar_ts in msg
            mystr.c_str()                    // <- take from here
            );
    */

    wcout << "After strcpy: \"" << msg << "\"" << endl;

    return 0;
}

#endif

我将让您阅读所有相关功能的文档。


0
投票

如果您想确保结果以零结尾,并且您可以在不合适的情况下截断字符串,那么最简洁的便携式解决方案可能是令人惊讶的snprintf

snprintf(msg, sizeof(msg), "%s", mystr.c_str());

其他答案有缺陷:

  • 使用 strcpy 你会面临缓冲区溢出的风险
  • 使用strncpy,如果缓冲区大小等于字符串长度,结果将不会以零结尾。您可以通过在第二步中将缓冲区以零终止来解决此问题,但这是额外的代码并且是 off-by-1 错误的常见来源。

-1
投票

使用strcpy函数: http://www.cplusplus.com/reference/clibrary/cstring/strncpy/

strncpy(msg, mystr.c_str(), sizeof msg / sizeof msg[0]);
msg[sizeof msg / sizeof msg[0] - 1] = 0; // null-terminate in case of truncation
© www.soinside.com 2019 - 2024. All rights reserved.