用printf输出string类型数据总结

来源:互联网 发布:网络管理培训课程 编辑:程序博客网 时间:2024/05/21 11:08

#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..." );

0 0
原创粉丝点击