Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //讀取檔案內容3
- //https://www.facebook.com/xiangyu.guo1/posts/2288195364542005
- //https://www.facebook.com/groups/1403852566495675/permalink/2189564644591126/
- //IDE:Microsoft Visual Studio Community 2017
- //author: Kuo, Hsiang-Yu
- //author: 90ED_7FD4_5B87
- #define _CRT_SECURE_NO_WARNINGS
- #include <cstdio>
- #include <cstdlib>
- #include <iostream>
- #include <string>
- #include <fstream>
- using namespace std;
- struct item
- {
- char id[10] = "";
- char name[10] = "";
- char type[10] = "";
- char year[10] = "";
- };
- int main(int argc, char *argv[])
- {
- system("color f0");
- int i = 0;
- struct item *data = NULL;
- fstream file;
- char buffer[80] = "";
- char input[10] = "";
- bool findData = false;
- int countLine = 0;
- file.open("C:\\Users\\acer\\Documents\\Visual Studio 2017\\Projects\\Sun_Chuan_Homework1\\test.txt", ios::in);
- if (!file)
- {
- cout << "檔案無法開啟。" << endl;
- system("pause");
- return 0;
- }
- else
- {
- cout << "開始讀取資料。" << endl;
- do
- {
- file.getline(buffer, sizeof(buffer));
- cout << buffer << endl;
- countLine = countLine + 1;
- } while (file.eof() == false);
- file.close();
- data = (struct item *)malloc(countLine * sizeof(struct item));
- file.open("C:\\Users\\acer\\Documents\\Visual Studio 2017\\Projects\\Sun_Chuan_Homework1\\test.txt", ios::in);
- i = 0;
- do
- {
- file.getline(buffer, sizeof(buffer));
- sscanf(buffer, "%s %s %s %s", &data[i].id, &data[i].name, &data[i].type, &data[i].year);
- i = i + 1;
- } while (file.eof() == false);
- file.close();
- cout << "資料讀取完畢。" << endl;
- }
- cout << endl;
- cout << "請輸入檢索資料:";
- cin >> input;
- cout << endl;
- for (i = 0; i < countLine; i++)
- {
- if (strcmp(input, data[i].type) == 0)
- {
- printf("%-8s%-7s%-8s%s\n", data[i].id, data[i].name, data[i].type, data[i].year);
- findData = true;
- }
- }
- if (findData == false)
- {
- cout << "查無資料。" << endl;
- }
- free(data);//釋放記憶體
- cout << endl;
- system("pause");
- return 0;
- }
Add Comment
Please, Sign In to add comment