C++学习笔记二——利用基本知识点编写小程序

今天买的ESSential C++ 这本书到了,粗略学习了第一章,主要回顾了几个重要的知识点,下面将介绍今天学习的内容。
自己编写了一个小程序,里面包含了C++一些知识点的基本使用,可以当做一个小例子练手。
该程序主要实现以下功能:
1)创建了斐波那契数列等一系列其他数列,显示其中的两个数,用户填写第三个数。
2)判断用户的数据是否正确,并询问用户是否愿意继续填写数据。
3)将用户的成绩按照名字存放在TXT文件中,如果想要查询成绩则输入名字进行查询。
以下是代码:

# include <iostream>
# include <fstream>
# include <string>
# include <vector>
# include <cstdlib>
# include <ctime>
using  namespace std;
int main()
{    // 初始化数列 包含 Fibonacci ,lucas 数列的前六个数
	const int size = 4;

	vector<int> fibo = { 1, 1, 2, 3, 5, 8 };
	vector<int> luca = { 1, 3, 4, 7, 11,18 };
	vector<int> pell = { 1, 2, 5, 12, 29,70 };
	vector<int> squre = { 1, 4, 9, 16, 25, 36 };
	//将指针初始化
	vector <int> *add[4] = { &fibo , &luca , &pell ,&squre };
	string name,name1;
	int right = 0, total = 0, value = 0;
	int index = 0;//索引,在四个数列中随机选取一个数列
	int index1 = 0;
	cout << "please input your name" << endl;
	cin >> name;
	char next = 'n';
	char go = 'y';

	while (go == 'y' ||  go == 'Y' )
	{
	
		srand((unsigned)time(0));//产生何种序列种子
		index = rand() % size;//产生0—3的随机数	
		index1 = rand() % 4;//产生0-3的随机数
	//填写数字
		
			cout << "请按照规律填写数字" << " " << add[index]->at(index1)
				<< " " << add[index]->at(index1 + 1) << endl;
			cin >> value;
			//判断输入的值是否正确
			if (value != add[index]->at(index1 + 2))
			{
				cout << "your anwser is wrong ,would you like to try again ? y/n" << endl;
				cin >> go;
				total++;

			}
			else
			{
				cout << "congratulations!,would you like to try again?y/n" << endl;
				cin >> go;
				right++;
				total++;
			}
			//将数据写进txt文件
			ofstream outfile("han.txt", ios_base::app);
			
			if (!outfile)//确认是否打开
				cout << "file is not open" << endl;

			else
			{
				//文件输入数据
				outfile << name << ' ' << right << ' ' << total << endl;


			}
	


		}

	cout << "game is over ,would you like to know your achievement? y/n" << endl;
	cin >> next;
	if (next == 'y' || next == 'Y')
	{
		ifstream infile("han.txt");
		if (!infile)
			cout << "error" << endl;
		else
		{  
			cout << "输入你想查询的成绩" << endl;
			cin >> name1;
			
			
			    vector <string> read;
				string read1;
				for (int i = 0;!infile.eof() ; i++)
				{   
					infile >> read1;
					read.push_back(read1);
				}
				//判断文件中是否有名字
				for (int i = 0; i < read.size(); i++)
				{  
					if (read[i] == name1)
						cout << "your achievement is " << ' ' << read[i]
						<< ' ' << read[i + 1] << ' ' << read[i + 2] << endl;
	
				}
		
			//
		}
	}

	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值