c++写日记簿程序,要求可以储存日记,并通过日期查找日记内容
时间: 2024-02-26 16:58:59 浏览: 27
好的,下面是一个简单的C++日记簿程序实现,可以储存日记,并通过日期查找日记内容:
```c++
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
using namespace std;
int main()
{
string filename = "diary.txt";
string content;
string input_date;
time_t now = time(0);
tm* ltm = localtime(&now);
int year = ltm->tm_year + 1900;
int month = ltm->tm_mon + 1;
int day = ltm->tm_mday;
int hour = ltm->tm_hour;
int minute = ltm->tm_min;
int second = ltm->tm_sec;
cout << "请输入日记内容:" << endl;
getline(cin, content);
ofstream outfile;
outfile.open(filename, ios::app);
outfile << year << "-" << month << "-" << day << " " << hour << ":" << minute << ":" << second << endl;
outfile << content << endl;
outfile << "----------------------------------------" << endl;
outfile.close();
cout << "日记已保存成功!" << endl;
cout << "请输入要查找的日期(例如:2022-02-01):" << endl;
cin >> input_date;
ifstream infile;
infile.open(filename, ios::in);
string line;
bool found = false;
while (getline(infile, line))
{
if (line.substr(0, 10) == input_date)
{
found = true;
cout << line << endl;
while (getline(infile, line) && line != "----------------------------------------")
{
cout << line << endl;
}
break;
}
}
infile.close();
if (!found)
{
cout << "没有找到对应日期的日记!" << endl;
}
return 0;
}
```
这个程序会提示用户输入日记内容,然后获取当前时间,最后将时间和内容写入到文件“diary.txt”中。用户可以输入要查找的日期,程序会从文件中读取对应日期的日记内容并输出。如果找不到对应日期的日记,则输出“没有找到对应日期的日记!”。