String data type: printf & cout output differently

Why is the output string irrecognizable by printf(%s)?

 

for example:

 

#include <iostream>
using namespace std;

int main()
{
char mywords[6] = "hello";

string mystring = mywords;

cout << "mywords : " << mywords << endl;//OKs
printf("mystring : %s/n", mystring); //error

return 0;
}

Printf is a C function, it is not support the class as an argument, but the String is the C++ class.

So, printf an string use %s is error. if you want to printf a string varible,you can printf("str = %s",mystring.c_str());

 

Printf output data only for build-in data type, but the string is not build-in, it's an extend class, so that , link error would  happen.string is not equal char*.

 

Printf output string can work in following way.

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


void main()
{
string aa="qqq";
printf("%s",aa.c_str());//or cout《a;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章