C++ HW9-1 for WallPower

將好友資料儲存到Friend資料結構,輸入時新增該筆資料到檔案,輸出時從檔案印出。
參考輸出如下。



  1. #include <iostream>
  2. #include <string>
  3. #include <fstream>
  4. using namespace std;
  5.  
  6. struct Data
  7. {
  8. string name, phone, bitthday;
  9. };
  10.  
  11. Data ReadData();
  12. void SaveFile(Data _Data, string Filepath);
  13. void ShowData(string FilePath);
  14. string FilePath = "\FriendData.txt";
  15. int select = 0;
  16.  
  17. int main()
  18. {
  19. while (1)
  20. {
  21. cout << "請問您要 1)輸出好友名單 2)新增好友資料:";
  22. cin >> select;
  23. if (select == 1)
  24. ShowData(::FilePath);
  25. else if (select == 2)
  26. SaveFile(ReadData(), ::FilePath);
  27. }
  28. return 0;
  29. }
  30.  
  31. Data ReadData()
  32. {
  33. Data temp;
  34. cout << "請輸入名稱:";
  35. cin >> temp.name;
  36. cout << "請輸入電話號碼:";
  37. cin >> temp.phone;
  38. cout << "請輸入生日:";
  39. cin >> temp.bitthday;
  40. return temp;
  41. }
  42.  
  43. void SaveFile(Data _Data, string FilePath)
  44. {
  45. fstream fs(FilePath, ios::app);
  46. fs << _Data.name << "\n";
  47. fs << _Data.phone << "\n";
  48. fs << _Data.bitthday << "\n";
  49. fs.close();
  50. }
  51.  
  52. void ShowData(string FilePath)
  53. {
  54. fstream fs(FilePath);
  55. string name;
  56. string phone;
  57. string birthday;
  58. while (!fs.eof())
  59. {
  60. getline(fs, name, '\n');
  61. getline(fs, phone, '\n');
  62. getline(fs, birthday, '\n');
  63. if (name == "")
  64. break;
  65. cout << "==============================================" << endl;
  66. cout << name << "的電話:" << phone << endl;
  67. cout << name << "的生日:" << birthday << endl;
  68. }
  69. fs.close();
  70. }

留言

這個網誌中的熱門文章

C# 井字遊戲