main
函數main
來執行一個 C++ 程式int main()
{
return 0;
}
main
函數要求返回值型別爲 int
,這是一個內建型別(built-in type)
型別(Types):定義了數據元素的內容以及可以在數據上進行的操作
用 echo $?
可以得到程式執行的返回值
iostream
istream, ostream
,分別表示輸入流和輸出流cin
:istream
型別的一個物件,表示標準輸入cout
:ostream
型別的一個物件,表示標準輸出cerr
:ostream
型別的一個物件,表示標準錯誤clog
:ostream
型別的一個物件,主要生成執行的資訊#include<iostream>
int main(){
std::cout << "Enter two numbers:" << std::endl;
int v1 = 0, v2 = 0;
std::cin >> v1 >> v2;
std::cout << "The sum of " << v1 << " and " << v2
<< " is " << v1 + v2 << std::endl;
return 0;
}
#include<iostream>
表示我們需要用到 iostream
庫,這是一個頭檔案main
裏面的第一個語句執行了一個 expression (有一個或多個 operator 構成的一個計算單元)<<
運算子接受兩個 operands,左邊必須是 ostream
的一個物件,右邊是一個需要輸出的值,這個運算子將給定的值寫到給定的 ostream
物件中去,得到的結果是其左邊的 operand,所以得到的結果仍然是一個 ostream
的物件,因此等價於:(std::cout << "Enter two numbers:") << std::endl;
以及
std::cout << "Enter two numbers:";
std::cout << std::endl;
endl
,這個東西叫做運運算元/操作符(manipulator),其作用是結束當前行,並重新整理裝置關聯的緩衝區,重新整理緩衝區(flushing the buffer)是爲了保證程式輸出的所有內容都已經寫到了輸出流中,而不是駐留在記憶體當中準備寫入。std::
表示 cout,endl
在 std
的名稱空間中進行定義int v1 = 0, v2 = 0
是在初始化兩個變數/* */
和 //
while
for
while(std::in >> value)
讀入直到 end-of-file (ctrl+d,win 是 ctrl+c)if
Sales_item
#include<iostream>
#include "Sales_item.h"
int main()
{
Sales_item book;
std::cin >> book;
std::cout << book << std::endl;
return 0;
}
Sales_item
#include<iostream>
#include "Sales_item.h"
int main()
{
Sales_item item1, item2;
std::cin >> item1 >> item2;
std::cout << item1 + item2 << std::endl;
return 0;
}
#include<iostream>
#include "Sales_item.h"
int main()
{
Sales_item item1, item2;
std::cin >> item1 >> item2;
if(item1.isbn() == item2.isbn()) {
std::cout << item1 + item2 << std::endl;
return 0;
} else {
std::cerr << "should refer to same ISBN" << std::endl;
return -1;
}
}
#include <iostream>
#include "Sales_item.h"
int main()
{
Sales_item total;
if(std::cin >> total) {
Sales_item trans;
while(std::cin >> trans) {
if(total.isbn() == trans.isbn())
total += trans;
else {
std::cout << total << std::endl;
total = trans;
}
}
std::cout << total << std::endl;
} else {
std::cerr << "no data?" << std::endl;
return -1;
}
}