我们许多人遇到了错误‘cannot convert std::string to char[] or char* data type’。
例如:
Input : string s = "geeksforgeeks" ;
Output : char s[] = { 'g', 'e', 'e', 'k', 's', 'f', 'o',
'r', 'g', 'e', 'e', 'k', 's' } ;
Input : string s = "coding" ;
Output : char s[] = { 'c', 'o', 'd', 'i', 'n', 'g' } ;
一种方法是将字符串的内容复制到char数组。这可以借助c_str()和strcpy()函数来完成。
c_str()函数用于返回指向数组的指针,该数组包含以空终止的字符序列,该字符串表示字符串的当前值。
语法:
const char* c_str() const;
如果抛出异常,则字符串中没有任何变化。但是,当我们需要查找或访问各个元素时,可以使用strcpy()函数将其复制到char数组中。复制后,我们可以像使用简单数组一样使用它。
采用的char数组的长度不应小于输入字符串的长度。
// CPP program to convert string
// to char array
#include <bits/stdc++.h>
using namespace std;
// driver code
int main()
{
// assigning value to string s
string s = "geeksforgeeks";
int n = s.length();
// declaring character array
char char_array[n + 1];
// copying the contents of the
// string to char array
strcpy(char_array, s.c_str());
for (int i = 0; i < n; i++)
cout << char_array[i];
return 0;
}
输出:
geeksforgeeks
另一种方法:
// CPP program to convert string
// to char array
#include <iostream>
#include <string.h>
using namespace std;
// driver code
int main()
{
// assigning value to string s
string s("geeksforgeeks");
// declaring character array : p
char p[s.length()];
int i;
for (i = 0; i < sizeof(p); i++) {
p[i] = s[i];
cout << p[i];
}
return 0;
}
输出:
geeksforgeeks