读取文本文件中的多行并写入另一个文本文件
Read multiple line in text file and write in another text file
这是我的分数.txt文件
7 2 11 4
9 1 30 3
5 3 20 3
10 1 10 2
5 0 50 0
这是 5 场板球比赛局的扣留
以上细节的结构:
在文本文件中,第一列表示 7 轮、2 次、11 次运行、4 次检票口。
我想在文本文件中获取五个投球手(计算列),并平均(第三列值除以第四列)并在终端中打印/显示。
如下所示:
Bowler Average
1 2.75
2 10
3 6.66
4 5
5 NA
6 NA
上面的文件有六个投球手,但最后一个是重复的。我尝试仅将其修复为五次,因为分数.txt文件有五行。
这是我的代码
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
using std::setw;
int main(){
float avg;
int over,maiden,runs,wickets;
ifstream scores;
scores.open("scores.txt");
if(!scores){
cout<<"Error n";
return -1;
}
ofstream average("average.txt");
if(!average){
cout<<"Error n";
return -1;
}
average << "Bowler"<<"t"<<"Average"<<endl;
int i=1;
//scores >> over >> maiden >> runs >> wickets;
while(!scores.eof()){
scores >> over >> maiden >> runs >> wickets;
avg = runs/float(wickets);
if(wickets == 0){
average<<i<<"t"<<"NA"<<endl;
}else{
//avg = runs/float(wickets);
average << i<<"t"<<avg<<endl;
}
i++;
}
scores.close();
average.close();
return 0;
}
我认为你的问题是这条线
while(!scores.eof()){
当你读完最后一行时,scores.eof()
false
,你尝试读另一行,读取失败(scores.eof()
变得true
),你不测试读数是否有错误,你使用最后一行值的两倍。
我建议类似
while( scores >> over >> maiden >> runs >> wickets ){
avg = runs/float(wickets);
相关文章:
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- C++试图读取一个文件并输出到另一个文本文件
- 如何从另一个文件继承私有成员变量和公共函数
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- C++ 如何打开带有另一个目录的输入文件?
- 如何在 Gnuplot 中分别绘制 2 个文件数据?我有一个文件"sin.txt",另一个文件"cos.txt",我想将它们分别绘制在一个图表上
- 从另一个 cpp 文件更改结构内、映射键内的变量
- 程序在使用 system() 启动另一个可执行文件时停止
- 如何在安卓工作室中将c ++头文件从一个文件夹导入到另一个文件夹?
- 如何在另一个 CPP 文件中使用一个 cpp 文件中的函数?
- 使用 scope 运算符 (::) 引用另一个文件中的类
- JNI,使用两个 .so 文件时出错,其中一个文件需要另一个文件
- 如何将包含另一个对象向量的对象保存到文件中,并使用C++中的二进制文件从文件中读回?
- 两个线程一个使用流 Api,另一个线程创建文件失败并出现错误ERROR_SHARING_VIOLATION
- 为什么我不能从同一目录中的另一个文件中 #include 我的类?
- 使用命名空间在另一个".cpp"文件中定义
- 在 c++ 中打开文件、删除标点符号并追加到另一个文件中
- C++ 如何将两个 makefile 对象目标规则(位于另一个文件夹中)合并到一个目标/规则中?
- 是否可以将子进程的 stdout 重定向到父进程中的另一个文件?