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

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;

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

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值