CPP_Basic_Code_P6.1-PP6.11.9

版权声明:本文虽为 贴墙上的咖啡 原创,未经允许仍可转载. https://blog.csdn.net/enochhugh/article/details/66508197

##CPP_Basic_Code_P6.1-PP6.11.9

//  The Notes Created by Z-Tech on 2017/2/17.
//	All Codes Boot on 《C++ Primer Plus》V6.0
//  OS:MacOS 10.12.4
//  Translater:clang/llvm8.0.0 &g++4.2.1
//  Editer:iTerm 2&Sublime text 3
//  IDE: Xcode8.2.1&Clion2017.1

//P6.1
#include <iostream>
int main()
{
    using std::cin;
    using std::cout;
    char ch;
    int spaces=0;//外部全局变量
    int total=0;//外部全局变量
    cin.get(ch);//读取第一个字符
    while (ch!='.')//如果不是句号则继续循环
    {
        if (ch==' ')
            ++spaces;//遇到空格计数
        ++total;//无论是否空格均计数,且字符总数包含最后的回车生成的换行符
        cin.get(ch);
    }
    cout<<spaces<<" spaces, "<<total
        <<" characters total in sentence\n";
    return 0;
}

//P6.2
#include <iostream>
int main()
{
    char ch;
    std::cout<<"Type,and I shall repeat.\n";
    std::cin.get(ch);
    while (ch!='.')
    {
        if (ch=='\n')
            std::cout<<ch;
        else
            std::cout<<++ch;//此处++ch被cout理解为字符输出,若改为ch+1则会被认为int输出
        std::cin.get(ch);
    }
    std::cout<<"\nPlease excuse the slight confusion.\n";
    return 0;
}

//P6.3
#include <iostream>
const int fave=9;
int main()
{
    using namespace std;
    int n;
    cout<<"Enter a number in the range 1-100 to find"
        <<"my favorite number: ";
    do{
        cin>>n;
        if (n<fave)//小了就说
            cout<<"Too low! Then guess again: ";
        else if (n>fave)//这种写法实际上是一个if else被包含在另一个if else中
            cout<<"Too high! Then guess again: ";
        else//这样调整后的写法实际上更清晰更好
            cout<<fave<<" is right!\n";
    }while (n!=fave);//没猜对就继续猜
    return 0;
}

//P6.4
#include <iostream>
int main()
{
    using namespace std;
    cout<<"This program may reformat your hard disk\n"//引号具有输出流连续性
            "and destroy all your data.\n"
            "Do you wish to continue? <y/n>";
    char ch;
    cin>>ch;
    if (ch=='y'||ch=='Y')//或运算符,或真则真,满足其一即可
        cout<<"You were warned!\a\a\n";
    else if (ch=='n'||ch=='N')//再次使用
        cout<<"A wise choice...Bye!\n";
    else
        cout<<"That's wasn't a 'Y/y' or 'N/n'!Apparently you "
            "can't follow\ninstructions,so "
            "I'll trash your disk anyway.\a\a\a\n";
    return 0;
}

//P6.5
#include <iostream>
const int ArSize=10;//控制数组大小,即报价个数
int main()
{
    using namespace std;
    float naaq[ArSize];
    cout<<"Enter the NAAQs (New Age Awareness Quotients) "
        <<"Of\nyour neighbors. Program terminates "
        <<"when you make\n"<<ArSize<<" entries "
        <<"or enter a negative value.\n";
    int i=0;
    float temp;
    cout<<"First value: ";
    cin>>temp;
    while (i<ArSize&&temp>=0)//第一个条件保证数组不溢出,第二个条件确保输入报价有效
    {
        naaq[i]=temp;//有效则逐个存入数组
        ++i;//数组角标自增
        if (i<ArSize)//然后如果i<ArSize说明数组还有空间,继续请求输入
        {
            cout<<"Next value: ";
            cin>>temp;//再次赋值给temp后继续循环直到存满数组
        }
    }
    if (i==0)//意味着输入了一个不满足第二个条件的数,于是未进入过while循环
        cout<<"No data--bye\n";//如果中途输入了负数则会跳过这里直接到下一模块请求自己报价,因为中途i!=0
    else
    {
        cout<<"Enter your NAAQ: ";//输入自己的报价
        float you;
        cin>>you;
        int count=0;//设定比较计数器
        for (int j=0;j<i;j++)//循环次数等于ArSize,也即是逐个比较
            if (naaq[j]>you)//如果之前报价你自己输入的高,则计数器+1
                ++count;//逐个比较直到循环结束
        cout<<count;//开始输出结果
        cout<<" of your naghbors have greater awareness of\n"
            <<"the New Age than you do.\n";
    }
    return 0;
}

//P6.6
#include <iostream>
const char* qualify[4]//创建指向字符串的常量指针数组
{
    "10,000-meter race.\n",
    "mud tug-of-war.\n",
    "masters canoe jousting.\n",
    "pie-throwing festival.\n"
};
int main()
{
    using namespace std;
    int age;
    cout<<"Enter your age in years: ";
    cin>>age;
    int index;

    if (age>17&&age<35)//18-34
        index=0;
    else if (age>=35&&age<50)//35-49
        index=1;
    else if (age>=50&age<65)//50-64,且可见else if可以连续使用
        index=2;
    else //包括负数,0-17,65以上;但是年龄默认不会输入负数
        index=3;
    cout<<"Your qualify for the "<<qualify[index];//输出分级页结果
    return 0;
}

//P6.7
#include <iostream>
#include <climits>
bool is_int(double);//函数声明
int main()
{
    using namespace std;
    double num;

    cout<<"Yo,dude!Enter an intger value: ";
    cin>>num;
    while (!is_int(num))//while条件函数调用取反
    {
        cout<<"Out if range __ Please try again: ";
        cin>>num;
    }
    int val=int (num);
    cout<<"You've entered the integer "<<val<<"\nBye\n";
    return 0;
}

bool is_int(double x)
{
    if (x<=INT_MAX&&x>=INT_MIN)
        return true;//输入范围成功则返回true,取反为false,则while被跳过
    else
        return false;//超出范围,返回false,取反为true,则while被激活,提示重新输入
}

//P6.8
#include <iostream>
#include <cctype>
int main()
{
    using namespace std;
    cout<<"Enter text for analysis and type @"
        " to terminate input.\n";
    char ch;
    int whitespace=0;
    int digits=0;
    int chars=0;
    int punct=0;
    int others=0;
    cin.get(ch);
    while (ch!='@')
    {
        if (isalpha(ch))//字母检查
            chars++;
        else if (isspace(ch))//空白符检查
            whitespace++;
        else if (isdigit(ch))//数字检查
            digits++;
        else if (ispunct(ch))//标点检查
            punct++;
        else
            others++;//剩下的归于其它,比如汉字等特殊符号
        cin.get(ch);
    }
    cout<<chars<<" letters, "
        <<whitespace<<" whitespace, "
        <<digits<<" digits, "
        <<punct<<" punctuations, "
        <<others<<" others.\n";
    return 0;
}

//P6.9
#include <iostream>//求出两个数最大值
int main()
{
    using namespace std;
    int a,b;
    cout<<"Enter two integers: ";
    cin>>a>>b;
    cout<<"The larger of "<<a<<" and "<<b;
    int c=a>b?a:b;//使用了?:条件运算符
    cout<<" is "<<c<<endl;
    return 0;
}

//P6.10.V1
#include <iostream>
using namespace std;
void showmenu();//无参无返回值函数声明
void report();
void comfort();
int main()
{
    showmenu();//函数调用显示菜单
    int choice;
    cin>>choice;
    while (choice!=5)
    {
        switch (choice)
        {
            case 1: cout<<"\a\n";
                    break;//跳出循环
            case 2: report();
                    break;
            case 3: cout<<"The boss was in all day.\n";
                    break;
            case 4: comfort();
                    break;
            default: cout<<"That's not a choice.\n";
            //缺省分支,后面不需要加break;
        }
        showmenu();
        cin>>choice;
    }
    cout<<"Bye!\n";
    return 0;
}

void showmenu()//菜单函数模块
{
    cout<<"Please enter 1,2,3,4,or 5:\n"
          "1) alarm         2) report\n"
          "3) alibi         4) comfort\n"
          "5) quit\n";
}
void report()//报告函数模块
{
    cout<<"It's been an excellent week for business.\n"
          "Sales are up 120$. Expense are down 35%.\n";
}

void comfort()//安抚模块
{
    cout<<"Your employees think you are the finest CEO\n"
          "in the industry .The board of directors thinks\n"
          "you are the finest CEO in the industry.\n";
}


//P6.10.V2
#include <iostream>
using namespace std;
void showmenu();//无参无返回值函数声明
void report();
void comfort();
int main()
{
    showmenu();//函数调用显示菜单
    char choice;//使用英文字符控制
    cin>>choice;
    while (choice!='Q'&&choice!='q')
    {
        switch (choice)
        {
            case 'a'://利用连续执行的特性解决大小写的问题
            case 'A': cout<<"\a\n";
                break;//跳出循环
            case 'b':
            case 'B': report();
                break;
            case 'c':
            case 'C': cout<<"The boss was in all day.\n";
                break;
            case 'd':
            case 'D': comfort();
                break;
            default: cout<<"That's not a choice.\n";//缺省分支,后面不需要加break;
        }
        showmenu();
        cin>>choice;
    }
    cout<<"Bye!\n";
    return 0;
}

void showmenu()//菜单函数模块
{
    cout<<"Please enter 1,2,3,4,or 5:\n"
            "a) alarm         b) report\n"
            "c) alibi         d) comfort\n"
            "q) quit\n";
}
void report()//报告函数模块
{
    cout<<"It's been an excellent week for business.\n"
            "Sales are up 120$. Expense are down 35%.\n";
}

void comfort()//安抚模块
{
    cout<<"Your employees think you are the finest CEO\n"
            "in the industry .The board of directors thinks\n"
            "you are the finest CEO in the industry.\n";
}

//P6.11
#include <iostream>
enum {red,orange,yellow,green,blue,violet,indigo};
//int类型 0,1,2,3,4,5,6
//枚举常量声明,没用变量名,注意逗号,结尾分号,和结构声明类似
int main()
{
    using namespace std;
    cout<<"Enter color code (0-6): ";
    int code;
    cin>>code;
    while (code>=red&&code<=indigo)//范围限定在0-6之间
    {
        switch (code)//标签
        {
            case red: cout<<"Her lips were red.\n";break;//注意此处有两个分号
            case orange: cout<<"Her hair was orange.\n";break;
            case yellow: cout<<"Her shoes were yellow.\n";break;
            case green: cout<<"Her nails were green.\n";break;
            case blue: cout<<"Her sweatsuit was blue.\n";break;
            case violet: cout<<"Her eyes were violet.\n";break;
            case indigo: cout<<"Her mood was indigo.\n";break;
        }
        cout<<"Enter color code (1-6)";
        cin>>code;
    }
    cout<<"Bye.\n";
    return 0;
}

//P6.12
#include <iostream>
const int ArSize=80;
int main()
{
    using namespace std;
    char line[ArSize];//设定字符数组
    int spaces=0;//初始化空格计数器
    cout<<"Enter a line of text:\n";
    cin.getline(line,ArSize);//字符读入line数组中
    cout<<"Complete line:\n"<<line<<endl;
    cout<<"Line through first period:\n";
    for (int i=0;line[i]!='\0';i++)//没碰到数组结尾\0将继续循环,逐个输出数组中的字符
    {
        cout<<line[i];
        if (line[i]=='.')//检测到句点则离开循环
            break;
        if (line[i]!=' ')//检测不到空格则回到for的循环更新处,即i++后继续循环
            continue;
        spaces++;//有空格将会到达此处,空格计数器
    }
    cout<<"\n"<<spaces<<" sapces\n";
    cout<<"Done.\n";
    return 0;
}

//P6.13
#include <iostream>
const int Max=5;
int main()
{
    using namespace std;
    double fish[Max];//初始化存重量的数组
    cout<<"Please enter the weights of your fish.\n";
    cout<<"You may enter up to "<<Max<<"fish <q to terminate>,\n";
    cout<<"fish #1: ";
    int i=0;
    while (i<Max&&cin>>fish[i])//且假则假,因此当左侧为false,右侧不会被判断,防止数组溢出
    {
        if (++i<Max)
            cout<<"fish #"<<i+1<<": ";//输出鱼的编号
    }
    double total =0.0;//设定重量计数器
    for (int j=0;j<i;j++)
        total+=fish[j];//统计整个数组的鱼总量
    if (i==0)
        cout<<"No fish\n";
    else cout<<total/i<<" = average weight of "<<i<<" fish\n";//计算平均值
    cout<<"Done.\n";
    return 0;
}

//P6.14
#include <iostream>//可阻止非法输入并给出正确的提示
const int Max=5;
int main()
{
    using namespace std;
    int golf[Max];
    cout<<"Please enter your golf scores.\n";
    cout<<"You must enter "<<Max<<" rounds.\n";
    int i;
    for (i=0;i<Max;i++)
    {
        cout<<"round #"<<i+1<<": ";
        while (!(cin>>golf[i]))//输入失败返回false,取反为true即启用错误处理
        {
            cin.clear();//重置cin
            while (cin.get()!='\n')//读取【行尾】之前所有的错误输入,从而删除这一行的错误输入
                continue;//循环直到cin.get()=='\n',也就是到达行尾
            cout<<"Please enter a number: ";
        }
    }
    double total=0.0;
    for (i=0;i<Max;i++)//求和模块
        total+=golf[i];
    cout<<total/Max<<" =average score "<<Max<<" rounds\n";
    return 0;
}

//P6.15
#include <iostream>
#include <fstream>//重要文件输入输出头文件
int main()
{
    using namespace std;
    char automobile[50];
    int year;
    double a_price;
    double d_price;

    ofstream outFile;//创建ofstream对象——outFile
    outFile.open("car_info.txt");//关联对象到文件
//以下是输入读取模块
    cout<<"Enter the make and model of automobile: ";
    cin.getline(automobile,50);
    cout<<"Enter the model year: ";
    cin>>year;
    cout<<"Enter the original asking price: ";
    cin>>a_price;
    d_price=0.913*a_price;
//以下是显示输出模块
    cout<<fixed;//输出格式修复
    cout.precision(2);//精度为小数点后2位有效数字
    cout.setf(ios_base::showpoint);//显示小数点
    cout<<"Make and model: "<<automobile<<endl;
    cout<<"Year: "<<year<<endl;
    cout<<"Was asking $"<<a_price<<endl;
    cout<<"Now asking $"<<d_price<<endl;
//以下是文件写入模块
    outFile<<fixed;//输出格式修复
    outFile.precision(4);//精度为小数点后4位有效数字
    outFile.setf(ios_base::showpoint);//显示小数点
    outFile<<"Make and model: "<<automobile<<endl;
    outFile<<"Year: "<<year<<endl;
    outFile<<"Was asking $"<<a_price<<endl;
    outFile<<"Now asking $"<<d_price<<endl;

    outFile.close();//关闭文件写入
    return 0;
}

//P6.16
#include <iostream>
#include <fstream>
//#include <cstdlib> //为支持exit()
const int SIZE=60;
int main()
{
    using namespace std;
    char filename[SIZE];
    ifstream inFile;//声明输入文件变量inFile
    cout<<"Enter name of data file: ";
    cin.getline(filename,SIZE);//读取文件名
    inFile.open(filename);//将inFile与filename关联
    if (!inFile.is_open())//输入成功则跳过,失败则激活
    {
        cout<<"Could not open the file "<<filename<<endl;
        cout<<"Program terminating.\n";
        exit(EXIT_FAILURE);
    }
    double value;
    double sum=0.0;
    int count=0;

    inFile>>value;//读取文件中第一个值
    while (inFile.good())//输入正常且未遇到EOF文件尾则继续循环,该方法没有出错时且不遇到EOF时返回均为true
    {
        ++count;
        sum+=value;
        inFile>>value;//继续读取文件下一个值
    }
    if (inFile.eof())//到此处说明循环结束到达文件尾,最后一次读取遇到EOF则返回true
        cout<<"End of file reached.\n";
    else if (inFile.fail())//检测到数据类型不匹配或遇到EOF时均会被激活返回true
        cout<<"Input terminated by data mismatch.\n";
    else//如果仍然不满足判断条件则说明失败原因未知
        cout<<"Input terminated by unknown reason.\n";
    if (count==0)//为true则说明未曾进入过读取循环体
        cout<<"No data processed.\n";
    else//一切正常则进入最终的读取状态统计报告
    {
        cout<<"Item read: "<<count<<endl;
        cout<<"Sum: "<<sum<<endl;
        cout<<"Average: "<<sum/count<<endl;
    }
    inFile.close();
    return 0;

}

//PP6.11.1
#include <iostream>
#include <cctype>
int main()
{
    using namespace std;
    cout<<"Please enter something: ('@' to quit)";
    char words;
    cin.get(words);//这比cin>>words更精细
    while (words!='@')
    {
        if (isalpha(words))
        {
            if (words>='a'&&words<='z')
                cout.put(toupper(words));//这里使用字符输出格式,cout默认十进制
            else
                cout<<char(tolower(words));//这是第二种方法,采用强制类型转换
        }
        //else if (words=='\n')//如果启用,检测到换行符即退出
        //    break;
        else
            cin.clear();//如果输入非字母字符,比如数字等,则重置cin
        cin.get(words);
    }
    return 0;
}

//PP6.11.2
#include <iostream>
#include <cctype>
int main()
{
    using namespace std;
    const int ArSize=5;
    int i=0,over_avrage=0;
    double tmp=0,sum=0,average=0;
    double donation[ArSize];
    cout<<"Enter the number: ";
    while (cin>>tmp&&i<ArSize)//此行代码不需要&&!isdigit(tmp),此法无效
    {
        donation[i]=tmp;
        sum+=donation[i];
        i++;
    }
    if (i!=0)//做商需要防止分母为0
        average=sum/i;//巧妙利用i
    for (int j=0;j<i;j++)
    {
        if (donation[j]>average)//找出大于平均值的数并计数
            ++over_avrage;
    }
    cout<<" sum: "<<sum<<" over_avrage: "<<over_avrage
        <<" i: "<<i<<" Average: "<<average;
    return 0;
}

//PP6.11.3
#include <iostream>
#include <cstdlib>//调用exit()函数必备
void show_menu();
void Select_c();
void Select_p();
void Select_t();
void Select_g();
void Select_q();
using namespace std;
int main()
{
    show_menu();
    char choice;
    cin.get(choice);
    while (choice)//任何选择都继续,意味着只能通过break;跳出循环结束任务
    {
        switch (choice)
        {
            case 'c':
            case 'C':Select_c();
                break;
            case 'p':
            case 'P':Select_p();
                break;
            case 't':
            case 'T':Select_t();
                break;
            case 'g':
            case 'G':Select_g();
                break;
            case 'q':
            case 'Q':Select_q();
                break;
            default:cout<<"That's not a choice.\n";//应对随意输入设计
        }
        show_menu();//此处是防止死循环的关键
        cin>>choice;
    }
    return 0;
}

void show_menu()//子函数括号右边不需要";"!
{
    cout<<"Please enter the following choice: (Use 'q' to quit.)\n"
          "c)Carnivo      p)Pianist\n"
          "t)Tree         g)Game\n";
}

void Select_c()
{
    cout<<"这个单词的意思是食虫植物。\n";
}
void Select_p()
{
    cout<<"钢琴家还是理查德厉害啊!\n";
}
void Select_t()
{
    cout<<"链表和二叉树又来了~\n";
}
void Select_g()
{
    cout<<"想玩游戏,你想多了吧\n";
}
void Select_q()
{
    exit(EXIT_FAILURE);//尝试调用失败返回值
}

//PP6.11.4
#include <iostream>
#include <cstdlib>//调用exit()函数必备
void show_menu();
void Select_a();
void Select_b();
void Select_c();
void Select_d();
void Select_q();
using namespace std;
struct bop
{
    string fullname;
    string title;
    string bopname;
    int preference;
};
int main()
{
    show_menu();
    char choice;
    cin.get(choice);
    bop* VIP=new bop[5];//指针指向结构数组
    VIP[0].fullname="HsuChou Yang";
    VIP[0].title="VVVIP";
    VIP[0].bopname="Z";
    VIP[0].preference=1;

    VIP[1].fullname="周杰伦";
    VIP[1].title="IP";
    VIP[1].bopname="Jay";
    VIP[1].preference=2;

    VIP[2].fullname="脸红的思春期";
    VIP[2].title="RSP";
    VIP[2].bopname="RFF";
    VIP[2].preference=0;

    VIP[3].fullname="金莎";
    VIP[3].title="Kim susu";
    VIP[3].bopname="Love";
    VIP[3].preference=1;

    VIP[4].fullname="沢井美空";
    VIP[4].title="SwaiMiku";
    VIP[4].bopname="美空";
    VIP[4].preference=2;

    while (choice)//
    {
        switch (choice)
        {
            case 'a':
            case 'A':
            {
                for (int i=0;i<5;i++)
                    cout<<VIP[i].fullname<<endl;
            };
                break;
            case 'b':
            case 'B':
            {
                for (int i=0;i<5;i++)
                    cout<<VIP[i].title<<endl;
            };
                break;
            case 'c':
            case 'C':
            {
                for (int i=0;i<5;i++)
                    cout<<VIP[i].bopname<<endl;
            };
                break;
            case 'd':
            case 'D':
            {
                for (int i=0;i<5;i++)
                //这一段是分解偏好的核心,使用if else顺利解决之
                {
                    if (VIP[i].preference==0)
                        cout<<VIP[i].fullname<<endl;
                    else if (VIP[i].preference==1)
                        cout<<VIP[i].title<<endl;
                    else
                        cout<<VIP[i].bopname<<endl;
                }
            };
                break;
            case 'q':
            case 'Q':
            {
                delete [] VIP;//注意释放指针
                exit(EXIT_FAILURE);
            }
        }
        show_menu();//此处是防止死循环的关键
        cin>>choice;
    }
    delete [] VIP;
    return 0;
}

void show_menu()//菜单函数,子函数括号右边不需要";"
{
    cout << "Please enter the following choice: (Use 'q' to quit.)\n"
            "a)display by name        b)display by title\n"
            "c)display by bopname     d)display by preference\n";
}

//PP6.11.5
#include <iostream>
int main()
{
    using namespace std;
    double salary,tax;
    cout<<"Please enter your salary first: \n";
    cin>>salary;
    while (salary>=0)
    {
        if (salary>=35000)
        {
            tax=(salary-35000)*0.2+20000*0.15+10000*0.1+0;
            break;
        }
        else if (salary>=15001)
        {
            tax=(salary-15000)*0.15+10000*0.1+0;
            break;
        }
        else if (salary>5000)
        {
            tax=(salary-5000)*0.1+0;
            break;
        }
        else if (salary<=5000)
        {
            tax=0;
            break;
        }
        else
        {
            tax=0;
            break;
        }
    }
    while (!cin)//输入不是数字将报错
    {
        cout<<"That's may not a number.\n";
        exit(EXIT_FAILURE);
    }

    cout<<"Tax that you need to pay: "<<tax<<"$"<<endl;
    return 0;
}

//PP6.11.6
#include <iostream>
const int ArSize=20;
const int num=5;
struct fund
{
    char name[ArSize];
    double money;
};
int main()
{
    using namespace std;
    int count=0,poor=0;//解决无人时none的显示
    fund* person=new fund[num];
    //以下是数据采集模块
    for (int i=0;i<num;i++)
    {
        cout<<"Please enter the name: ";
        cin.get(person[i].name,ArSize);
        cout<<"Please enter the money: ";
        cin>>person[i].money;
        if (!cin)
        {
            cout<<"Wrong number! Please run again. ";
            exit(EXIT_FAILURE);
        }
        cin.get();//至关重要,使用cin输入double后需要读取回车
    }
    cout << "Grand Patrons: \n";//开始输出重要人物
    for (int i=0;i<num;i++)
    {
        if (person[i].money > 10000)
        {
            cout << person[i].name << " : " << person[i].money <<"$"<<endl;
            count++;
        }
    }
    if (count == 0)
        cout << "none.\n";
    cout<<"Patrons: \n";//开始输出一般捐献者
    for (int i=0;i<num;i++)
    {
        if (person[i].money<=10000)
        {
            cout<<person[i].name<<endl;
            poor++;
        }
    }
    if (poor==0)
        cout<<"none.\n";
    delete [] person;
    return 0;
}

//PP6.11.7
#include <iostream>
#include <cctype>
#include <cstring>
const int ArSize=20;
int main()
{
    using namespace std;
    char word[ArSize];
    int vowel=0,consonants=0,others=0;
    cout<<"Please enter the words: \n";
    cin>>word;
    cout<<word;
    while (strcmp(word,"q"))//警告!不能用赋值号比较字符串!
    {
        if (isalpha(word[0]))//检测是否字母
        {
            if (word[0]=='a'||word[0]=='e'||word[0]=='i'||word[0]=='o'||word[0]=='u')
            //是否元音字母
                vowel++;
            else
                consonants++;//否则辅音字母
        }
        else
            others++;//其余杂项统计
        cin>>word;
    }
    cout<<"Vowel: "<<vowel<<"\nConsonants: "<<consonants<<"\nOthers: "<<others<<endl;
    return 0;
}


//PP6.11.8
#include <iostream>
#include <fstream>
int main()
{
    using namespace std;
    char filename[20];
    int count=0;
    ifstream inFile;
    cout<<"Enter name of file: ";
    cin.getline(filename,20);
    inFile.open(filename);
    if (!inFile.is_open())
    {
        exit(EXIT_FAILURE);
    }

    char ch;
    inFile.get(ch);//使用cin将忽略空格,使用get()将不会忽略空格
    while (inFile.good())//使用good检查文件读取是否正常,是否抵达文件尾
    {
        count++;
        inFile.get(ch);
    }
    cout<<count<<" characters reads.\n";
    inFile.close();
    return 0;
}

//PP6.11.9
#include <iostream>
#include <fstream>
const int ArSize=20;
int num=0;//创建的动态结构指针数组成员数
struct fund
{
    char name[ArSize];
    double money;
};
int main()
{
    using namespace std;

    //以下是数据初始化模块
    int count=0,poor=0;//解决无人时none的显示
    fund* person=new fund[num];
    char filename[ArSize];
    cout<<"Please enter the file name: ";
    cin.getline(filename,ArSize);
    fstream inFile;
    inFile.open(filename);

    //以下是文件打开成功检测
    if (!inFile.is_open())
    {
        cout<<"Fail to open the file.\n";
        exit(EXIT_FAILURE);
    }

    //以下是数据读取模块
    inFile>>num;//读取应该创建的结构数
    inFile.get();//读取数组后再读取换行符
    for (int i=0;i<num;i++)
    {
        inFile.get(person[i].name,ArSize).get();//读取名字后读取换行符
        inFile>>person[i].money;//读取double,注意读取方式
        inFile.get();//读取换行符
        if (inFile.eof())
        {
            cout<<"End of file reached:OK!\n";
        }
        else if (inFile.fail())
        {
            cout<<"Input terminated by data mismatch.\n";
        }
        else
            continue;
    }
    cout<< "Grand Patrons: \n";//开始输出重要人物
    for (int i=0;i<num;i++)
    {
        if (person[i].money > 10000)
        {
            cout << person[i].name << " : " << person[i].money <<"$"<<endl;
            count++;
        }
    }
    if (count == 0)
        cout << "none.\n";
    cout<<"Patrons: \n";//开始输出一般捐献者
    for (int i=0;i<num;i++)
    {
        if (person[i].money<=10000)
        {
            cout<<person[i].name<<endl;
            poor++;
        }
    }
    if (poor==0)
        cout<<"none.\n";
    delete [] person;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/enochhugh/article/details/66508197
pp
6.1