C++编程思想第二章部分课后习题记录

2.4 识别文件中S的个数,目前只能识别到以空格隔开,与2.3类似


#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
	ifstream in("helloworld2.cpp");
	string s;
	string flag = "s";
	int i = 0;
	while (in >> s)
	{
		if (s == flag)
		{
			i++;
		}
	}
	cout << "Number of words = " << i << endl;
}

2.5 将循环的逻辑次数进行修改就行

//: C02:Fillvector.cpp
//Copy an entire file into a vector of string #include <string>
#include <iostream> 
#include <fstream> 
#include <vector> 
#include <string>
using namespace std;
int main() {

	vector<string> v;
	ifstream in("Fillvector.cpp");
	string line;
	while (getline(in, line))
		v.push_back(line); 
	for (int i =0; i < v.size(); i++)
		cout << v.size()-1-i << ": " << v[v.size()-1-i] << endl; //更改部分
} 

2.6

//: C02:Fillvector.cpp
//Copy an entire file into a vector of string #include <string>
#include <iostream> 
#include <fstream> 
#include <vector> 
#include <string>
using namespace std;
int main() {

	vector<string> v;
	ifstream in("Fillvector.cpp");
	string line,addlines;
	while (getline(in, line))
		v.push_back(line); 
	for (int i =0; i < v.size(); i++)
		 addlines += v[i] ; //关键部分
	cout << addlines;
} 

2.7 

//: C02:Fillvector.cpp
//Copy an entire file into a vector of string #include <string>
#include <iostream> 
#include <fstream> 
#include <vector> 
#include <string>
using namespace std;
int main() {

	//vector<string> v;
	ifstream in("Fillvector.cpp");
	string line;
	while (getline(in, line))
	{
		cout << line;//没有换行符
		cin.get();//用户输入回车键
	}

}		

2.8 字符串数据堆入后,在遍历输出即可、

#include <iostream> 
#include <vector> 
#include <string>
using namespace std;
int main() {

	vector<float> v;
	for (int i = 0; i < 25; i++)
		v.push_back(i + 0.9);
	for (int i = 0; i < v.size(); i++)
		cout << v[i] << " ";

}	

2.9 

//: C02:Fillvector.cpp
#include <iostream> 
#include <vector> 
#include <string>
using namespace std;
int main() {

	vector<float> v1;
	vector<float> v2;
	vector<float> v3;
	for (int i = 0; i < 25; i++)
	{
		v1.push_back(i + 0.9);
		v2.push_back(i + 0.8);	
	}
	for (int i = 0; i < 25; i++)
	{
		v3.push_back(v1[i] + v2[i]);
	}

	for (int i = 0; i < 25; i++)
	{
		cout << v3[i]<< endl;
	}
}	

2.10

//: C02:Fillvector.cpp
#include <iostream> 
#include <vector> 
#include <string>
using namespace std;
int main() {

	vector<float> v1;

	for (int i = 0; i < 25; i++)
	{
		v1.push_back(i + 0.9);
	}
	for (int i = 0; i < 25; i++)
	{
		cout << "first out :" << v1[i]<<"\t";
	}
	cout << endl;
	for (int i = 0; i < 25; i++)
	{
		v1[i] = v1[i] * v1[i];
	}
	for (int i = 0; i < 25; i++)
	{
		cout << "second out :" << v1[i]<<"\t";
	}
	cout << endl;
}	

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值