c++_单词本

刚开始学习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;

}

运行结果如下:


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值