C++中string和string.h的作用和區別

來源:互聯網
上載者:User

#include < string .h >

void main()
{
string aaa = " abcsd d " ;
printf( " looking for abc from abcdecd %s\n " ,
(strcmp(aaa, " abc " )) ? " Found " : " Not Found " );

}

不能正確執行,提示說是string 類型沒有定義

而下面:

#include < string >

using namespace std;
void main()
{
string aaa = " abcsd d " ;
printf( " looking for abc from abcdecd %s\n " ,
(strcmp(aaa, " abc " )) ? " Found " : " Not Found " );
}

這裡的string編譯器就認識了,但是strcmp就不認識了呢?

一般一個C++的老的帶“。h”副檔名的庫檔案,比如 iostream.h,在新標準後的標準庫中都有一個不帶“。h”副檔名的 相對應,區別除了後者的好多改進之外,還有一點就是後者的東東都塞進了 “std”名字空間中。

但唯獨string特別。

問題在於 C++要相容C的標準庫,而C的標準庫裡碰巧也已經有一個名字叫做 “string.h”的標頭檔,包含一些常用的C字串處理函數,比如樓 主提到的strcmp.

這個標頭檔跟C++的string類半點鐘關係也沒有,所以 <string>並非<string.h>的“升級版本”,他們是毫無 關係的兩個標頭檔。

要達到樓主的目的,比如同時:

#include < string .h >
#include < string >
using namespace std;

或者

#include < cstring >
#include < string >

其中<cstring>是與C標準庫 的<string.h>相對應,但裹有std名字空間的版本。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.