这是一个老掉牙的话题, 但是你稍加不注意就会出错.
最近在写一个可以跨平台打印的程序,就遇到这个问题,故记之.共勉!
用 char 数组初始化string
#include <string> using std::string; using std::cout; int main(int argc, const char * argv[]) { char chArray[] = {'m', 'a', 'r', 'k'}; cout << "array size = " << sizeof(chArray)/sizeof(char) << endl; cout << chArray << endl; string str(chArray); cout << "str = " << str << " and str's size = " << str.length() << endl; }
在 mac 平台下,输出结果
array size = 4 mark\310\367\277_\377 str = mark\310\367\277_\377 and str's size = 10
但是有时候输出结果又是这样的
array size = 4 mark str = mark and str's size = 5很明显, string 的 size 不对.
思考一下,原来是少了 ‘\0‘, 修改上面代码
#include <string> using std::string; using std::cout; int main(int argc, const char * argv[]) { char chArray[] = {'m', 'a', 'r', 'k', '\0'}; cout << "array size = " << sizeof(chArray)/sizeof(char) << endl; cout << chArray << endl; string str(chArray); cout << "str = " << str << " and str's size = " << str.length() << endl; }
array size = 5 mark str = mark and str's size = 4
另外,要注意, string 的 size 要比 char 数组 size 小.
不知道上面的东西,你有没有看明白?
那么下面的代码输出,你觉得会达到自己的预期吗?
const char * cp = str.c_str(); unsigned long size = str.length(); char chArray2[size]; for (int i=0; i<size; i++) { chArray2[i] = cp[i]; cout << chArray2[i] << endl; } string str2(chArray2); cout << "str2 = " << str2 << " and str2's size = " << str2.length() << endl;
ok, 这里很显然是错误的,至少两处是不对的.
1. chArray2的大小
2. chArray2的结束符没有添加 ‘\0‘
修改一下, 给出完整示例
#include <string> using std::string; using std::cout; int main(int argc, const char * argv[]) { // char[] ---> string char chArray[] = {'m', 'a', 'r', 'k', '\0'}; cout << "array size = " << sizeof(chArray)/sizeof(char) << endl; cout << chArray << endl; string str(chArray); cout << "str = " << str << " and str's size = " << str.length() << endl; // string --> char[] const char * cp = str.c_str(); unsigned long size = str.length(); char chArray2[size + 1]; for (int i=0; i<size; i++) { chArray2[i] = cp[i]; cout << chArray2[i] << endl; } chArray2[size] = '\0'; string str2(chArray2); cout << "str2 = " << str2 << " and str2's size = " << str2.length() << endl; }
的确,是这样,但是有时候需要 char 数组来操作,我也是把自己遇到的问题,加以总结跟大家分享一下.
把示例代码中的
char chArray[] = {'m', 'a', 'r', 'k', '\0'};
char chArray[] = "mark";
const char *chArray = "mark";
原文地址:http://blog.csdn.net/veryitman/article/details/45402587