C++ HW9-1 for WallPower
將好友資料儲存到Friend資料結構,輸入時新增該筆資料到檔案,輸出時從檔案印出。
參考輸出如下。
參考輸出如下。
#include <iostream> #include <string> #include <fstream> using namespace std; struct Data { string name, phone, bitthday; }; Data ReadData(); void SaveFile(Data _Data, string Filepath); void ShowData(string FilePath); string FilePath = "\FriendData.txt"; int select = 0; int main() { while (1) { cout << "請問您要 1)輸出好友名單 2)新增好友資料:"; cin >> select; if (select == 1) ShowData(::FilePath); else if (select == 2) SaveFile(ReadData(), ::FilePath); } return 0; } Data ReadData() { Data temp; cout << "請輸入名稱:"; cin >> temp.name; cout << "請輸入電話號碼:"; cin >> temp.phone; cout << "請輸入生日:"; cin >> temp.bitthday; return temp; } void SaveFile(Data _Data, string FilePath) { fstream fs(FilePath, ios::app); fs << _Data.name << "\n"; fs << _Data.phone << "\n"; fs << _Data.bitthday << "\n"; fs.close(); } void ShowData(string FilePath) { fstream fs(FilePath); string name; string phone; string birthday; while (!fs.eof()) { getline(fs, name, '\n'); getline(fs, phone, '\n'); getline(fs, birthday, '\n'); if (name == "") break; cout << "==============================================" << endl; cout << name << "的電話:" << phone << endl; cout << name << "的生日:" << birthday << endl; } fs.close(); }
留言
張貼留言