error: cannot convert ‘const String’ to ‘const char*’ for argument ‘1’ to ‘size_t strlen(const char*)’ data =new char[strlen(str) + 1];
时间: 2024-04-14 19:27:19 浏览: 34
这个错误是因为你在将一个 `String` 对象转换为 `const char*` 时出错了。`strlen` 函数的参数应该是一个以 null 结尾的字符串,而不是一个 `String` 对象。要解决这个问题,你可以使用 `c_str()` 函数来获取 `String` 对象的 C 风格字符串表示,然后再传递给 `strlen` 函数。修改代码如下所示:
```cpp
data = new char[str.length() + 1];
strcpy(data, str.c_str());
```
这样就可以正确地将 `String` 对象的内容复制到 `data` 字符数组中了。记得在不需要使用 `data` 时释放内存,避免内存泄漏。
相关问题
cannot convert'char'to'const char*'for argument'1' to 'size_t strlen (const char*)
这个错误通常是因为你在使用 strlen 函数时传入了一个 char 类型的参数,但是 strlen 函数需要的是一个 const char* 类型的参数。
你需要将参数转换为 const char* 类型,可以使用如下代码进行转换:
```c++
char c = 'a';
const char* str = &c; // 转换为 const char* 类型
size_t len = strlen(str);
```
注意,上面的代码只是一个示例,实际上 char 类型的参数并不是常见的使用方式,通常是使用字符串字面量或者 char 数组作为参数传入 strlen 函数。
[error] cannot convert 'std::string {aka std::basic_string<char>}' to 'const char*' for argument '1' to 'size_t strlen(const char*)'
错误:无法将'std :: string {aka std :: basic_string <char>}'转换为'const char *',用于参数'1'到'size_t strlen(const char *)'
这个错误是因为您尝试将一个std :: string对象传递给一个期望接受const char *参数的函数。strlen()函数期望一个指向以null结尾的字符数组的指针,而不是一个std :: string对象。
要解决此错误,您需要将std :: string对象转换为const char *。您可以使用c_str()函数将std :: string对象转换为const char *。例如:
std::string str = "Hello World";
const char *cstr = str.c_str();
size_t len = strlen(cstr);
现在,您可以将cstr传递给strlen()函数,而不会出现错误。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)