"C++ Programming Thoughts (Two Volumes Combined Edition)" Chapter 2 After-Class Exercises Some Questions and Assignment Records
(Tool: VS2019)
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
using namespace std;
//打开文件并从后往前打印各行
void readFileFromBackToFront() {
vector<string> sentence;
string s;
ifstream in("D:\\aaaJemma\\QTtest\\vector\\test.txt");
while (getline(in, s)) {
sentence.push_back(s);
}
for (int i = sentence.size() - 1; i >= 0; i--) {
cout << sentence[i]<<endl;
}
}
//打开文件并统计文件中以空格隔开的单词数目
void getFileWordNum() {
vector<string> words; //存放多个string
string word;
int num = 0;
ifstream in("D:\\aaaJemma\\QTtest\\vector\\test.txt"); //打开文件用于读
while (in >> word) {
//一次传送一个单词
num++;
words.push_back(word);
}
cout << "num:" << num << " words.size():" << words.size()<<endl;
}
//打开文件并将所有单词连接成一个字符串
void getFileAString() {
//vector<string> words; //存放多个string
string word,sentence;
int num = 0;
ifstream in("D:\\aaaJemma\\QTtest\\vector\\test.txt"); //打开文件用于读
while (in >> word) {
//一次传送一个单词
sentence += word;
}
cout << sentence << endl;
}
//创建一个vector,并输入多个浮点数
void vectorAndFloat() {
vector<float> vf;
float f = 1.02;
for (int i = 0; i < 25; i++) {
vf.push_back(f);
f += i;
}
for (int j = 0; j < vf.size(); j++) {
cout << vf[j] << " ";
}
}
//两个vector相加
void vectorAddvector() {
vector<float> vf1,vf2,vf3;
float f1 = 1.02,f2=8.79;
for (int i = 0; i < 25; i++) {
vf1.push_back(f1);
f1 += i;
vf2.push_back(f2);
f2 += i;
}
for (int n = 0; n < 25; n++) {
vf3.push_back(vf1[n] + vf2[n]);
}
for (int j = 0; j < vf1.size(); j++) {
cout << "vf1:" << vf1[j] << " vf2:" << vf2[j] << " vf3:" << vf3[j] << endl;
}
}
//打开文件,等待用户输入回车后输出一行
void vectorCinThenCout() {
vector<string> v;
ifstream in("D:\\aaaJemma\\QTtest\\vector\\test.txt");
string line;
while (getline(in, line)) {
cout << line;
cin.get();
}
}
int main()
{
std::cout << "Hello World!\n";
getFileWordNum();
cout << endl<<"2.打开文件并统计文件中以空格隔开的单词数目"<<endl;
readFileFromBackToFront();
cout << endl<<"3.打开文件并将所有单词连接成一个字符串"<<endl;
getFileAString();
cout << endl << "4.打开文件,等待用户输入回车后输出一行" << endl;
vectorCinThenCout();
cout << endl << "5.创建一个vector,并输入多个浮点数" << endl;
vectorAndFloat();
cout << endl << "6.两个vector相加" << endl;
vectorAddvector();
}