用printf输出string类型 cannot pass objects of non-POD

 1 #include <apue.h>
  2 #include <iostream>
  3 #include <string>
  4 using namespace std;
  5
  6 void swap(string &s1, string &s2);
  7
  8 int
  9 main(int argc, char *argv[])
 10 {   
 11     if(argc != 3)
 12         err_sys("Usage: swp_strref stringA stringB");
 13     
 14     string s1 = argv[1];
 15     string s2 = argv[2];
 16     cout<<"stringA: "<<s1<<"\t"<<"stringB: "<<s2<<"\nAfter change..."<<endl;
 17 //  printf("stringA: %s\tstringB: %s\nAfter change...\n", s1, s2);
 18     swap(s1, s2);
 19     cout<<"stringA: "<<s1<<"\t"<<"stringB: "<<s2<<endl;
 20 //  printf("stringA: %s\tstringB: %s\n", s1, s2);
 21     
 22     exit(0);
 23 }


使用printf输出string类型时候出现错误:warning: cannot pass objects of non-POD type 'struct std::string' through '...'; call will abort at runtime.

baidu以后在网站 http://blogold.chinaunix.net/u2/76292/showart.php?id=2314559 找到了解决办法,

printf只能输出C语言内置的数据,而string不是内置的,只是一个扩展的类,这样肯定是链接错误的。 string不等于char*,&a代表的是这个字符串的存储地址,并不是指向字符串的首地址,aa    对象中包含一个指向"string"的指针, &aar得到的是这个对象的地址,不是"string"的地址。

printf输出string类型应如此操作!

#include<iostream>
#include<string>
using namespace std;


void main()
{
string aa="qqq";
printf("%s",aa.c_str()); //不推荐

//或者cout<<a;
}

由于string是C的一个 扩展类型,其数据赋值可以用其提供的方法:assign(const char *)或直接用其构造函数      
string str( "Now is the time..." );

转载于:https://www.cnblogs.com/xminghua/p/6649422.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值