【问题标题】:Why I am fail my convert string to a C-string trying this way?为什么我尝试以这种方式将字符串转换为 C 字符串失败?
【发布时间】:2020-08-10 06:44:09
【问题描述】:

我在 VS2019 中的代码不起作用。 在最后一行代码编译器抛出错误。

#include <iostream>
#include <string>
using namespace std;

struct struct1
{
    string name;
};

void main()
{
    struct1* obj1 = new struct1();
    obj1->name = "Hello";

    // compiler says 'initializing': cannot convert from 'const _Elem *' to 'char [25]'
    char str[25] = (obj1->name).c_str();

}

【问题讨论】:

  • 初始化数组是行不通的。
  • 很难理解当您拥有string 时为什么要将其复制到数组中。正如您发现的那样,数组非常有限。

标签: c++ string c-strings


【解决方案1】:

c_str() 返回一个指向字符串字符数据的start 的指针。您需要使用 strncpy() 之类的方式将字符复制到数组中。

【讨论】:

    【解决方案2】:

    有很多方法可以做到这一点 但首先你应该改变 char 数组初始化的方式,因为你做错了。

    这是同一个程序,但工作正常

    #include <iostream>
    
    using namespace std;
    
    struct struct1
    {
        string name;
    };
    
    
    
    int main()
    {
        struct1* obj1 = new struct1();
        obj1->name = "Hello";
        char str[25] = "";
        memcpy(&str,obj1->name.c_str(),obj1->name.size());
        cout << str << endl;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-03-13
      • 1970-01-01
      • 2020-05-24
      • 2016-03-11
      • 2015-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多