c++ - 阅读格式不一致的文本文件
问题描述
我正在尝试对包含重复的基于 C 的字符串和一些数字的文本文件执行一些操作。我的代码成功地在第一组上执行了操作,但它不会到达剩余的组。
请查看以下文本文件的内容:
Max Scherzer 2017
6.2 4 2 2 2 7
6.0 4 3 1 2 10
mod Cameron 2018
6.4 4 1 2 1 3
6.0 4 3 5 2 8
John Brandonso 2019
6.1 1 3 5 2 7
6.5 4 7 3 4 10
我已经使用过.eof()
,它完全搞砸了我正在做的事情。
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
char playername [25];
int season;
ifstream gamefilein;
gamefilein.open("C:\\Users\\troy\\Desktop\\GAME_SCORE\\gameinfo.txt");
if(!gamefilein)
{
cout<<"unable to open file";
}
double IP;
int H,R,ER,BB,K;
int counter=0;
double totalscore=0;
while(!gamefilein.fail())
{
gamefilein.get(playername,25);
gamefilein>>season;
cout<<playername<<season<<endl;
cout<<"Game Scores:"<<endl;
while(gamefilein>>IP>>H>>R>>ER>>BB>>K)
{
int IPa=IP;
int IPb=(IP-IPa)*10;
int IPc=0;
if(IPa>4)
{
IPc=IPa-4;
}
int score=50+(IPa*3)+(IPb*1)+(IPc*2)+(K*1)-(H*2)-(ER*4)-((R-ER)*2)-(BB*1);
cout<<score<<endl;
counter++;
totalscore+=score;
}
cout<<"Number of Games Started: "<<counter<<endl;
cout<<fixed<<setprecision(2)<<"Average Game Score:
<<(totalscore/counter)<<endl<<endl;
}
gamefilein.close();
return 0;
}
我得到了以下结果,但我希望文本文件中的其余信息得到相同的结果,例如,我期待另外两个结果,如下面的结果。
Max Scherzer 2017
Game Scores:
63
64
Number of Games Started: 2
Average Game Score: 63.50
解决方案
我自己解决了我的问题。当对整数和双精度进行操作的循环完成其运行并看到下一个数据集中的基于字符的字符串时,就会出现问题。所以我在检查文件结尾(gamefilein.clear())的地方插入了一个清晰的成员函数,这解决了我的问题。
感谢您尝试提供帮助
推荐阅读
- vue.js - Vuetify:将对象属性引用传递给 v-for 中的文本字段
- python - 尝试使用python删除列中的一些数据
- jquery - 如何将模态弹出窗口添加到数据表
- r - 如何使用 ggplot2 在条形图上放置标签?
- c - 最长公共子序列不打印长度矩阵
- react-native - 通过单击按钮重置选择器
- javascript - React - 如何使用上下文访问挂钩值
- javascript - 如何加载 Bootstrap 选项卡内容?
- python - 'core' 不是注册的命名空间 Django
- windows - Git 使用 SourceTree 和 Bitbucket 克隆存储库:错误服务器意外关闭网络连接