ifstream ifs("speech.csv", std::ios::in);
if (!ifs.is_open())
{
//std::cout << "文件不存在" << std::endl;
this->fileIsEmpty = true;
ifs.close();
return;
}
char ch;
ifs >> ch;
if (ifs.eof())
{
//std::cout << "文件为空" << std::endl;
this->fileIsEmpty = true;
ifs.close();
return;
}
//文件不为空
this->fileIsEmpty = false;
ifs.putback(ch);
std::string data;
int round = 0;
while (ifs >> data)
{
//定义获取往届比赛信息的容器
std::vector<std::string> v;
int pos = -1; //,号的标志位
int start = 0;
while (true)
{
//寻找 以","号分割的字符串,找不到就结束
pos = data.find(",", start);
if (pos == -1)
{
break;
}
//substr(起始位置, 结束位置)
std::string temp = data.substr(start, pos - start);
start = pos + 1;
v.push_back(temp);
}
//将往届的冠军数据插入到容器中
this->m_Record.insert(std::map<int, std::vector<std::string>>::value_type(round, v));
++round;
}
ifs.close();
}
在 speechManager
构造函数中调用获取往届记录函数
SpeechManager::SpeechManager()
{
//初始化
this->initSpeaker();
//创建选手
this->createSpeaker();
//查看往届记录
this->loadRecord();
}
6.2 查看记录功能
在 speechManager.h
中添加保存记录的成员函数 void showRecord();
//显示往届得分
void showRecord();
在 speechManager.cpp
中实现成员函数 void showRecord();
void SpeechManager::showRecord()
{
if (this->fileIsEmpty)
{
std::cout << "文件不存在,记录为空" << std::endl;
}
else
{
for (int i = 0; i < this->m_Record.size(); i++)
{
std::cout
<< "=========第" << i + 1 << "届=========" << "\n"
<< "冠军编号: " << this->m_Record[i][0] << " 得分: " << this->m_Record[i][1] << "\n"
<< "亚军编号: " << this->m_Record[i][2] << " 得分: " << this->m_Record[i][3] << "\n"
<< "季军编号: " << this->m_Record[i][4] << " 得分: " << this->m_Record[i][5] << "\n"
<< "========================" << "\n"
<< std::endl;
}
}
system("pause");
system("cls");
}
6.3 bug解决
目前程序中有几处bug未解决:
-
查看往届记录,若文件不存在或为空,并未提示
解决方式:在 showRecord
函数中,开始判断文件状态并加以判断
-
若记录为空或不存在,比完赛后依然提示记录为空
解决方式:saveRecord
中更新文件为空的标志
-
比完赛后查不到本届比赛的记录,没有实时更新
解决方式:比赛完毕后,所有数据重置
-
在初始化时,没有初始化记录容器
解决方式:initSpeech
中添加 初始化记录容器
每次记录都是一样的
解决方式:在main函数一开始 添加随机数种子
srand((unsigned int)time(NULL));
7. 清空记录
7.1 清空记录功能实现
在 speechManager.h
中添加保存记录的成员函数 void clearRecord();
//清空记录
void clearRecord();
在 speechManager.cpp
中实现成员函数 void clearRecord();
void SpeechManager::clearRecord()
{
int choise = 0;
std::cout << "确定要清空全部的数据吗?" << std::endl;
std::cout << "1.确定 ------ 0.返回" << std::endl;
std::cin >> choise;
if (choise == 1)
{
std::ofstream ofs("speech.csv", std::ios::trunc);
this->initSpeaker();
this->createSpeaker();
this->loadRecord();
std::cout << "清空完成!" << std::endl;
}
std::cout << "取消清空操作" << std: