KuoHsiangYu

讀取檔案內容3

Oct 15th, 2018
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.04 KB | None | 0 0
  1. //讀取檔案內容3
  2. //https://www.facebook.com/xiangyu.guo1/posts/2288195364542005
  3. //https://www.facebook.com/groups/1403852566495675/permalink/2189564644591126/
  4. //IDE:Microsoft Visual Studio Community 2017
  5. //author: Kuo, Hsiang-Yu
  6. //author: 90ED_7FD4_5B87
  7.  
  8. #define _CRT_SECURE_NO_WARNINGS
  9.  
  10. #include <cstdio>
  11. #include <cstdlib>
  12. #include <iostream>
  13. #include <string>
  14. #include <fstream>
  15.  
  16. using namespace std;
  17.  
  18. struct item
  19. {
  20.     char id[10] = "";
  21.     char name[10] = "";
  22.     char type[10] = "";
  23.     char year[10] = "";
  24. };
  25.  
  26. int main(int argc, char *argv[])
  27. {
  28.     system("color f0");
  29.  
  30.     int i = 0;
  31.     struct item *data = NULL;
  32.     fstream file;
  33.     char buffer[80] = "";
  34.     char input[10] = "";
  35.     bool findData = false;
  36.     int countLine = 0;
  37.  
  38.     file.open("C:\\Users\\acer\\Documents\\Visual Studio 2017\\Projects\\Sun_Chuan_Homework1\\test.txt", ios::in);
  39.  
  40.     if (!file)
  41.     {
  42.         cout << "檔案無法開啟。" << endl;
  43.         system("pause");
  44.         return 0;
  45.     }
  46.     else
  47.     {
  48.         cout << "開始讀取資料。" << endl;
  49.  
  50.         do
  51.         {
  52.             file.getline(buffer, sizeof(buffer));
  53.             cout << buffer << endl;
  54.             countLine = countLine + 1;
  55.         } while (file.eof() == false);
  56.         file.close();
  57.  
  58.         data = (struct item *)malloc(countLine * sizeof(struct item));
  59.  
  60.         file.open("C:\\Users\\acer\\Documents\\Visual Studio 2017\\Projects\\Sun_Chuan_Homework1\\test.txt", ios::in);
  61.         i = 0;
  62.         do
  63.         {
  64.             file.getline(buffer, sizeof(buffer));
  65.             sscanf(buffer, "%s %s %s %s", &data[i].id, &data[i].name, &data[i].type, &data[i].year);
  66.             i = i + 1;
  67.         } while (file.eof() == false);
  68.         file.close();
  69.  
  70.         cout << "資料讀取完畢。" << endl;
  71.     }
  72.     cout << endl;
  73.  
  74.     cout << "請輸入檢索資料:";
  75.     cin >> input;
  76.  
  77.     cout << endl;
  78.     for (i = 0; i < countLine; i++)
  79.     {
  80.         if (strcmp(input, data[i].type) == 0)
  81.         {
  82.             printf("%-8s%-7s%-8s%s\n", data[i].id, data[i].name, data[i].type, data[i].year);
  83.             findData = true;
  84.         }
  85.     }
  86.  
  87.     if (findData == false)
  88.     {
  89.         cout << "查無資料。" << endl;
  90.     }
  91.    
  92.     free(data);//釋放記憶體
  93.    
  94.     cout << endl;
  95.     system("pause");
  96.     return 0;
  97. }
Add Comment
Please, Sign In to add comment