我正在尝试对一个包含重复的基于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发布于 2019-04-26 05:50:29
您不是将文件作为char数组读取吗?
如果我没看错的话,你会尝试在字符串中包含数字的char数组上移位int和double,对吧?
例如," 6.2“字符串不同于你记忆中的6.2双精度数,因此它不能工作。
你似乎也有很多不应该忘记的空间。
你是从哪里得到这个字符串的?我建议您将该文件的创建更改为更方便的格式,例如cv或json
发布于 2019-04-26 10:59:31
我刚刚自己解决了我的问题。当对整数和双精度进行操作的循环完成其运行并查看下一个数据集中的基于字符的字符串时,就会出现此问题。所以我在检查文件结尾的地方插入了一个明确的成员函数(gamefilein.clear()),这就解决了我的问题。
感谢您的帮助
https://stackoverflow.com/questions/55855754
复制相似问题