C++中string類

來源:互聯網
上載者:User

標籤:

1.C中通過字元數組來儲存字串,而C++中通過string類來儲存並處理字串。<string>

#include<string>#include<iostream>using namespace std; int main(){       string str1,str2;    //Null 字元串    string str3 = "Hello C++!";        //初始化    string str4("I am");    //初始化    str2 = "Today";        //賦值    str1 = str3 + " " +str4;    //組合字元串    str1 += " 8 ";    cout<<str1 + str2 + "!"<<endl;    return 0;}/*輸出:E:\myDocuments\GUN\C++>Demo.exeHello C++! I am 8 Today!E:\myDocuments\GUN\C++>*/

  兩種初始化方法,直接用+和=操作。

2.檔案讀寫<fstream>,它會自動包含<iostream>,書中建議如果是有cout和cin最好顯示引入<iostream>

  ①為了讀而開啟一個檔案,建立對象ifstream,用法與cin相同,資料是從磁碟到記憶體裡面

  ②為了寫而開啟一個檔案,建立對象ofstream,用法與cout相同,資料時從記憶體到外部磁碟中。

//copy one file to another ,a line at one time#include<iostream>#include<fstream>using namespace std; int main(){       ifstream In("Demo.cpp");    //讀取Demo.cpp檔案    ofstream Out("Demo2.cpp");    //寫入檔案Demo2.cpp檔案    string STR1;    while(getline(In,STR1))        Out<<STR1<<"\n";        return 0;}/*輸出:E:\myDocuments\GUN\C++>g++ Demo.cpp -o  Demo.exeE:\myDocuments\GUN\C++>Demo.exeE:\myDocuments\GUN\C++>dir 磁碟機 E 中的卷是 DATA 卷的序號是 EC10-1C79 E:\myDocuments\GUN\C++ 的目錄2015-08-25  13:59    <DIR>          .2015-08-25  13:59    <DIR>          ..2015-08-25  13:58               333 Demo.cpp2015-08-25  13:58           497,380 Demo.exe2015-08-25  13:59               333 Demo2.cpp   --------------------新添的檔案2015-08-21  09:52               111 GUN.bat               4 個檔案        498,157 位元組               2 個目錄 81,163,862,016 可用位元組*/

3.string對象具有動態特性,不必擔心string的記憶體配置

  

//把一個檔案的拷貝到一個string對象中#include<iostream>#include<fstream>#include<string>using namespace std; int main(){       ifstream In("Demo.cpp");    //讀取Demo.cpp檔案        string STR,line;    while(getline(In,line))        STR += line + "\n";        cout<<STR;        return 0;}/*輸出:E:\myDocuments\GUN\C++>g++ Demo.cpp -o  Demo.exeE:\myDocuments\GUN\C++>Demo.exe//把一個檔案的拷貝到一個string對象中#include<iostream>#include<fstream>#include<string>using namespace std;int main(){        ifstream In("Demo.cpp");        //讀取Demo.cpp檔案        string STR,line;        while(getline(In,line))                STR += line + "\n";        cout<<STR;    return 0;}E:\myDocuments\GUN\C++>*/

 

C++中string類

聯繫我們

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