C++ 编程思想 第一卷课后练习题

来源:互联网 发布:vue.js 时间格式化 编辑:程序博客网 时间:2024/05/01 22:32
 2-3 编写一个程序用来打开文件并统计文件中以空格隔开的单词数目。 

ifstream f2("D:\\test.txt");if(!f2)return 1;int wordsNumber = 0 ;char c ;bool spaceRepeat = false ;while((c = f2.get()) != EOF){cout << c ;if(c == ' ' && !spaceRepeat){++wordsNumber ;spaceRepeat = true;}else if(c != ' ')spaceRepeat = false;}cout << "\n\nThe sentence has " << ++wordsNumber << " words." << endl;f2.close();


2-4 编写一个程序统计文件中特定单词的出现次数(要求使用string类的运算符 "==" 来查找单词)。 

ifstream inf("d:\\test.txt");if(!inf)return 1;string word;int num = 0 ;while(inf >> word){if(word == "is" || word == "is!"|| word == "is."){++num;}}cout << "is 出现的次数为:" << num << "次" << endl ;inf.close();

2-5 修改Fillvector.cpp 使它能从后向前打印各行。 

vector<string> fill_vec ;ifstream fill_in("d:\\test.txt");if(!fill_in)return 1;string line ;while(getline(fill_in,line)){fill_vec.push_back(line);}for(int i = fill_vec.size()-1  ; i >= 0 ; --i){cout << fill_vec[i] << endl;}


2-7 编写一个程序,一次显示文件的一行,然后,等待用户按回车键后显示下一行。

vector<string> fill_vec ;ifstream fill_in("d:\\test.txt");if(!fill_in)return 1;string line ;while(getline(fill_in,line)){fill_vec.push_back(line);}for(int i = fill_vec.size()-1  ; i >= 0 ; --i){cout << fill_vec[i] << endl;//system("pause");//第一种方法:输入回车显示下一行//cin.get();//第二种方法:输入回车显示下一行,cin.get()不忽略回车//getchar();//第三种方法:输入回车显示下一行}