# C++的基礎架構 編者:111年初階教學趙炫翔 --- ## 標準程式庫標頭檔 標頭檔就像一部字典 當你include(引入)不同的函式庫 就像翻開了不同功能的字典 而`iostream`就是其中一個 ```cpp= #include<iostream> ``` ## 主程式碼(主函式) 每個`C++`的程式都包含一到或多個函式,其中一個必須被命名為`main` 而作業系統會先呼叫`main`函式(函式後會在後頭詳細介紹) ```cpp= #include<iostream> int main(){ //程式碼 } ``` ## 命名空間 我們可以舉一個例子 如果我們引入一個函式庫叫高中 而建中和武陵都有400班這個函式 那我們就可以用命名空間來確定我們現在用的是建中的還是武陵的400班 ```cpp= #include<iostream> using namespace std; int main(){ //程式碼 } ``` `using namespace std;` 就是代表接下來的程式碼都是用`std`這個命名空間 :::info :::spoiler 補充知識 命名空間是一種識別編號,不同功能的函式有可能有相同的功能 所以就需要給它們一個編號,來讓電腦確定我們要的是哪一個以避免衝突 而`C++`標準庫就是定義在`std`之下的 所以要達到讓電腦成功辨識的目的,其實也可以這樣寫 ```cpp= #include<iostream> int main(){ std::cout << "Hello, world" << std::endl; return 0; } ``` `cout`這個函式是在標準庫之中的程式碼 所以我們需要`std::`標記是在`std`這個命名空間底下 ::: ## 輸出/輸入 :::info :::spoiler 補充知識 `cout`(輸出)和`cin`(輸入)都是被定義在`std`命名空間和`iostream`函式庫 所以必須要引入該函式空間和命名空間才能使用 ::: ### 輸出文字 ```cpp= cout << "任意文字";//句子結尾要有分號 ``` `""`包字串、`''`包字元 "string" 'c' ```cpp= #include<iostream> using namespace std; int main(){ cout << "Hello, world";//輸出 Hello, world } ``` endl/(end of line) 可以讓輸出換行 不過我們常常會使用`'\n'` `'\n'`的運行速度比較快 ```cpp= #include<iostream> using namespace std; int main(){ cout << "Hello, world" << endl; cout << "Hello, world" << '\n'; cout << "Hello, world\n"; //輸出三行 Hello, world } ``` ### 輸出運算式子 ```cpp= cout << 運算式; ``` ```cpp= #include<iostream> using namespace std; int main(){ cout << "23+2=" << 23+2 << endl;//輸出23+2=25 return 0; } ``` ### 輸入 ```cpp= cin >> 變數名稱;//變數會在之後介紹 ``` ```cpp= #include<iostream> using namespace std; int main(){ int value;//這是變數,之後會介紹 cin >> value; //程式碼 } ``` ## 程式暫停 ```cpp= #include<iostream> using namespace std; int main(){ cout << "Hello, world" <<'\n'; system('pause'); //程式碼 } ``` `system('pause')`在執行檔(exe)才看的到效果 當程式讀到`system('pause')`時程式會強制暫停 :::warning 在`dandanjudge`丟程式碼時不要寫`system('pause')`會卡住 ::: ## 回傳值 ```cpp= #include<iostream> using namespace std; int main(){ cout << "Hello, world" <<'\n'; return 0; } ``` `return 0`是代表一個主函式的結束 在許多編輯器如果沒有`return 0`,他會幫你自動結束主函式 但最好還是養成習慣寫,有些如果沒寫會無法編譯
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up