错误代码如下:
char szStr[256] = {0};
sprintf(szStr, "%s",whatever);
m_str = string(szStr);
printf("------str is %s",m_str);
报错如下:
WorkThread.cpp:144: warning: cannot pass objects of non-POD type `struct std::string' through `...'; call will abort at runtime
WorkThread.cpp:144: warning: format argument is not a pointer (arg 2)
如果忽视warning,运行会出现Segmentation fault。
修改:
将printf那行改为C++风格打印即可:
cout<<"---------str is"<
总结:
C与C++字符串处理存在差异,C的字符串自己申请数组,自己拼装,直接%s打印即可;C++将字符串封装成类,使用可以说更加方便,但要注意别用混。