本日購入したESSentialC ++の本はこちらです。最初の章を大まかに勉強し、主にいくつかの重要な知識のポイントを復習しました。以下では、今日の研究の内容を紹介します。
私は、C ++のいくつかの知識ポイントの基本的な使用法を含む小さなプログラムを作成しました。これは、練習の小さな例として使用できます。
プログラムは主に次の機能を実現します
。1)フィボナッチ数列などの他の一連のシリーズを作成し、そのうちの2つを表示し、ユーザーが3番目の数字を入力します。
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;
}
//
}
}
}