刚开始学习C++,写了一个单词本的程序,用来记录每天背诵的单词
代码如下:
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
inline void keep_window_open() {char ch;cin>>ch;}
int main()
{
cout<<"您好,欢迎使用单词记录本。"<<endl;
cout<<"您可以每天输入您阅读的英语单词,做个记录。"<<endl;
fstream f;
f.open("word.txt",ios_base::in);
bool flag_new_file=false;
if(!f)
{
cout<<"出错:单词本不存在,在当前目录创建新的单词本。"<<endl;
f.open("word.txt",ios_base::in|ios_base::app);//只读,文件不存在则创建
if(!f)
{
cout<<"出错:创建失败,退出应用程序。请按任意键退出。"<<endl;
return 0;
}
else
{
cout<<"修复:成功创建单词本。"<<endl;
flag_new_file=true;
}
}
int num=0;
int num_temp;
char s[20];
char an;
while(an!='Y'&&an!='N')
{
cout<<"是否要查看单词本的所有单词?回复Y或者N:";
cin>>an;
if(an=='Y')
{
while(!f.eof()) {
f.getline(s,20);
num++;
cout<<num<<"."<<s<<endl;
}
}
else if(an=='N')
{
while(!f.eof()) {
f.getline(s,20);
num++;
}
}
}
f.close();
if(flag_new_file)
{
num--;
}
else
{
cout<<endl;
cout<<"回顾:你已经背诵了"<<num<<"个单词。";
cout<<"上一个单词是:"<<endl;
cout<<num<<"."<<s<<endl;
}
num_temp = num;
f.open("./word.txt",ios_base::out|ios_base::app);
cout<<"请输入今天阅读的单词,退出请输入单词:finish"<<endl;
string ss;
num++;
cout<<num<<".";
cin>>ss;
while(ss.compare("finish"))//不相同返回1
{
if(flag_new_file)
{
flag_new_file=false;
}
else
{
f<<endl;//换到下一行的开头。
}
f<<ss;
num++;
cout<<num<<".";
cin>>ss;
}
num--;//去掉最后一个单词finish的计数。
cout<<"你今天阅读了"<<num-num_temp<<"个单词," \
<<"总共阅读了"<<num<<"个单词。"<<endl;
f.close();
cout<<"请按任意键退出。"<<endl;
keep_window_open();
return 0;
}
运行结果如下: