# 陣列 - C語言中處理大量資料的方式 - Array陣列 - 陣列的使用方式 - 先==宣告== - `資料型態宣告字(int,float) 自己取的陣列名字[數量]` - `int std[20]` - 再==使用== - `陣列名字[1]`這就是陣列的第一個元素 - `std[19] = 某整數` - for迴圈是陣列的好朋友(這頁下方都是C++寫的) ```cpp= #include <iostream> #include <string> using namespace std; int main() { string fruit[5]; for (int i = 0; i < 5; i++) { cout << "輸入第" << i + 1 << "顆水果種類:"; cin >> fruit[i]; } for (int i = 0; i < 5; i++) { cout << "第" << i + 1 << "顆水果種類是:" << fruit[i] << endl; } } ``` - 可以做個txt檔輸入陣列 - 把檔案變成串流 ```cpp= #include <fstream> //f=file:檔案 ... ... ... ifstream fruitList("fruitList.txt"); string fruit; fruitList >> fruit; cout << fruit << endl; ``` 但這樣只會印出清單第一個水果,所以要利用==迴圈==改良 ```cpp= #include <iostream> #include <string> #include <fstream> using namespace std; int main() { ifstream fruitList("fruitList.txt"); string fruit[2]; for (int i = 0; i < 5; i++) { fruitList >> fruit[i]; } for (int i = 0; i < 2; i++) { cout << fruit[i] << endl; } } ``` 如果想要存更多種資料,在文字檔案中這樣表示: ``` 1 芭樂 20 2 鳳梨 45 3 蘋果 100 ``` 宣告順序可以不一樣,但出現順序要一樣 ```cpp= #include <iostream> #include <string> #include <fstream> using namespace std; int main() { //匯入與宣告區 ifstream fruitList("fruitList.txt"); int no; string fruit; int love; //印3次 for (int i = 0; i < 3; i++) //執行幾次 { fruitList >> no >> fruit >> love; cout << "第" << no << "個" << fruit << "的喜好程度:" << love << endl; } } file.close(); //記得關掉,不然其他程式可能無法存取,也會佔用記憶體 return 0; ``` - 把上方`istream`改成`ofstream`可輸出檔案 - 配合`cin` - 檔案流的位置要改到下方 ```cpp= #include <iostream> #include <string> #include <fstream> using namespace std; int main() { //匯出指令與宣告區 ofstream fruitList2("fruitList2.txt"); string fruit; int love; //輸入區 cout << "你常吃的水果是?請輸入水果名稱:"; cin >> fruit; cout << "你覺得有幾分喜歡?請輸入整數:"; cin >> love; //匯出功能 fruitList2 << fruit << love; } ``` - file有自己的指令 - 備註:跳過物件檔的編譯方法 - `g++ -o *.exe *.cpp` - `*.cvs`是種用逗點隔開值的檔案
×
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