c++中怎么把string转化为数组

如题所述

有很多种方法,在这儿列出两种。

1、因为string可以看作是数组构成的串,所以直接定义一个char的指针,指过去就可以了。

示例如下:

#include <windows.h>  
#include <stdio.h>  
#include <time.h> 
#include <iostream>
using namespace std;
int main()
{

    string s1 = "abcdeg"; //定义string
    const char *k; //定义char指针
    k = s1.c_str(); //让指针指向s1的位置

    cout << k[0] << endl; //测试输出k指针指向的第一个字符

    system("pause"); //暂停一下以便查看
    return 0;  //标准的返回退出

}

2、比较机械的,先定义一个字符数组,然后将字串的内容“复制”进去。这种方法更规矩一些,也更安全一些:

#include <windows.h>  
#include <stdio.h>  
#include <time.h> 
#include <iostream>
using namespace std;


int main()
{

    string s = "a1234";
    char c[20];
    strcpy(c, s.c_str());

    cout << c[0] << endl;

    system("pause");
    return 0;

}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-11-15
CString类是没有位数要求的,CString位数是系统自动调整的。
char型数组需要先定义位数。
只有char位数大于或等于string型位数了,才能转换,否则就会造成数据提示和程序崩溃。
第2个回答  2016-11-15
string s="1234";
char c[20];
strcpy(c,s.c_str());
这样才不会出错,c_str()返回的是一个临时指针,不能对其进行操作
相似回答