c++ - 为什么我尝试以这种方式将字符串转换为 C 字符串失败?
问题描述
我在 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();
}
解决方案
c_str()
返回指向字符串字符数据开头的指针。您需要使用类似strncpy()
.
推荐阅读
- sql - 使用实体框架插入大量重复数据
- python - 如何在 Pandas 中连接包含列表(系列)的两列
- azure-devops - VSTS 配置代理池和队列
- linux - 本地针对远程文件的 Ag 命令
- arrays - 如何在打字稿中定义一个常量数组
- reactjs - 在知道 id 时添加 refs 以响应组件
- javascript - 研究什么来解决这类问题?
- php - WP 站点某些 url 重定向到 WP 中的外部 URL
- laravel - 永久 Cookie 包含敏感会话信息 Laravel 使用 Appscan 安全工具
- django-views - django动态过滤不返回预期结果