C++中sprintf和string的使用问题

来源:互联网 发布:手机屏幕养兔子软件 编辑:程序博客网 时间:2024/06/09 15:13

C++中sprintf和string的使用问题

关于string在sprintf中格式化的问题,用一段代码来说明问题:

string str1 = "string1";string str2 = "string2";string str3 = "string3";char ch[50];memset(ch, '\0', sizeof ch);sprintf(ch, "str1 = %s, str2 = %s, str3 = %s", str1, str2, str3);cout<<ch<<endl;

在VS2010中编译,结果出现下面异常:
Cplusplus.exe 中的 0x0fdf14cf (msvcr100d.dll) 处有未经处理的异常: 0xC0000005: 读取位置 0x69727473 时发生访问冲突。
经过调试,发现出错语句为 sprintf处,但是不知道是哪里有问题。一直以来都是这样使用CString类的,所以以为string类也是一样的可以如此使用,string类直接匹配%s。最后发现,必须要使用string类中的成员变量去赋值才行,所以应该按如下修改:

string str1 = "string1";string str2 = "string2";string str3 = "string3";char ch[50];memset(ch, '\0', sizeof ch);sprintf(ch, "str1 = %s, str2 = %s, str3 = %s", str1.c_str(), str2.c_str(), str3.c_str());cout<<ch<<endl;

如此修改后,运行结果正常。

原创粉丝点击