--- tags: 初階班 --- # C++ 基礎架構 ## 標頭檔 標頭檔就是函式庫,每個程式都需要引入標頭檔才能使用裡面的功能。 ```cpp= #include <iostream> ``` 也可以引入多個標頭檔以使用更多功能 ## 命名空間 一樣的程式可能有不同的功能,所以我們需要命名空間來讓程式判斷現在要的是哪種功能。 就像上海和桃園都有復旦,如果要程式知道現在講的是桃園的復旦,就需要命名空間。 因為`std`是`c++`系統標準的命名空間,因此可以在程式一開始加上`using namespace std;` ```cpp= #include <iostream> using namespace std; ``` ## 主程式 每個C++程式都會有一個以上的函式,而一定需要一個叫`main`的主函式來執行。 ```cpp= #include <iostream> using namespace std; int main(){ //程式碼 } ``` :::info :::spoiler 補充 其中`int main()`的`int`代表程式最後會回傳一個整數值到作業系統,而`()`代表使用`main`時不用傳入任何參數 ::: ## 輸出&輸入 下面的東西基本上都是寫在主程式`int main()`裡面 ### 輸出 ```cpp= #include <iostream> using namespace std; int main(){ cout << "一串文字"; } ``` 用`""`把字串包起來,字元(只有一個字)用`''`包(但用`""`也可以) #### 輸出換行 `\n`或`endl`(end of line) ```cpp= #include <iostream> using namespace std; int main(){ cout << "Hello, world" << '\n'; cout << "Hello, world\n"; cout << "Hello, world" << endl; //輸出三行Hello, world } ``` 兩者的功能是一樣的(就換行),但時間上`'\n'`比`endl`快很多 #### 輸出運算式 ```cpp= #include <iostream> using namespace std; int main(){ cout << 1+2 << '\n'; //輸出3 cout << 3*4 << '\n'; //輸出12 } ``` #### 輸出變數 變數在之後會介紹 輸出的語法是 ```cpp= #include <iostream> using namespace std; int main(){ int n = 3; //宣告一個名稱為n、值為3的int變數(之後會介紹) cout << n; //輸出n的值也就是3 } ``` ### 輸入 輸入到一個變數 ```cpp= #include <iostream> using namespace std; int main(){ int n; //宣告int變數n,之後介紹 cin >> n; //輸入值到n } ``` :::info :::spoiler 命名空間 標準輸出輸入都是建立在`std`命名空間之下,因此如果在一開始沒有加上`using namespace std`的話輸出也可以改成這樣打: ```cpp= #include <iostream> int main(){ std::cout << "Hello, world" << std::endl; return 0; } ``` 讓程式辨認現在使用的是`std`命名空間 :::