第一個程序demo.cpp
編譯、運行
g++ -c demo.cpp
g++ -o demo.exe demo.o
解釋
最簡單的C++源文件
1 int main() {
2 return 0;
3}
使用cout 輸出一行字符串
1 //this is sample for study
2 #include <iostream>
3
4 int main() {
5 std::cout << "This is a sample for study." << std::endl;
6 return 0;
7 }

Screen Shot 2022-03-24 at 1.36.51 PM.png
使用命名空間
1 //this is sample for study
2 #include <iostream>
3
4 using namespace std;
5 int main() {
6 cout << "This is a sample for study." << endl;
7 return 0;
8 }
使用變量
1 //this is sample for study
2 #include <iostream>
3
4 using namespace std;
5 int main() {
7 int carrots;
8
9 carrots = 25;
10 cout << "I have " << carrots << " carrots." << endl;
11
12 carrots = carrots - 1;
13 cout << "Crunch, Crunch. Now I have "<< carrots << " carrots." << endl;
14 return 0;
15 }
從鍵盤輸入
1 //this is sample for study
2 #include <iostream>
3
4 using namespace std;
5 int main() {
6 cout << "This is a sample for study." << endl;
7 int carrots;
8
9 carrots = 25;
10 cout << "I have " << carrots << " carrots." << endl;
13
14 cout << "Please input number:";
15 cin >> carrots;
16
17 cout << "Now ,I still hava " << carrots << " carrots." << endl;
18
19 return 0;
20 }