標籤:
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類