用printf輸出string類型資料總結

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.