您的位置:首页 > 其它

用printf输出string类型数据总结

2008-04-14 22:26 369 查看
#include <stdio.h>

#include <string.h>
using namespace std;
int main()
{
string a;
a[0]='a';
a[1]='/0';
printf("%s/n",a);
system("pause");
}

出错: [Warning] cannot pass objects of non-POD type `struct std::string' through `...'; call will abort at runtime

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..." );
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: