如何让我的代码显示文件名不正确或文件中数字的平均值?



我的代码应该要求一个文件名,获取该文件,然后使用其中的数字来计算数字的平均值。但是,它将平均值显示为 0,并且无论是否有错误,它也始终显示错误消息和平均值。

我尝试将检查它是否失败的 if 语句移动到 main,以便它可以轻松地在那里结束,并尝试使用 if 语句在出现错误时使其结束。

#include <iostream>
#include <fstream>
using namespace std;
bool getFileName();
void display(float ave);
float readFile(char fileName[]);
int main()
{
char fileName[256];
float ave;
getFileName();
display(ave);
return 0;
}

bool getFileName()
{ 
char fileName[256];
ifstream fin("file.txt");
cout << "Please enter the filename: ";
cin >> fileName;
if (fin.fail())
{
cout << "Error reading file "" << fileName << """ << endl; 
return 0;
}
else
return fileName;
} 

float readFile(char fileName[])
{
char text[256];
int i;
ifstream fin("file.txt");
int num;
int total;
for (fin >> text; i++;)
{
num += total;
}
fin.close();
float ave = total / i;
return ave;
}  

void display(float ave)
{
cout << "Average Grade: " << ave << "%" << endl;
return;
}

预期:

Average Grade: (ave)% 

Error reading file "fileName"

实际:

Error reading file "fileName"
Average Grade: (ave)%

这是一个适度的选择:

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
std::string getFileName() {
std::string fileName;
std::cout << "Please enter the filename: ";
std::cin >> fileName;
return fileName;
}
double compute_average(std::string fileName) {
std::ifstream fin(fileName);
if (!fin.is_open()) {
throw std::runtime_error("Unable to open file " + fileName);
}
int ct = 0;
double total = 0.0l;
std::string line;
while (std::getline(fin, line)) {
double num = std::stod(line, nullptr);
total += num;
ct++;
}
fin.close();
double ave = total / (double)ct;
return ave;
}
void display(float ave) {
std::cout << "Average Grade: " << ave << "%" << std::endl;
return;
}
int main() {
std::string fileName = getFileName();
try {
double ave = compute_average(fileName);
display(ave);
}
catch (std::exception &e) {
std::cout << e.what();
}
return 0;
}

笔记:

  1. "main()"移动到底部通常很方便,然后再向上滚动以更详细地查看前面的代码。

  2. 省略"使用 std"通常很有用,可以快速查看您的依赖项。

  3. 您不想对"file.txt"进行硬编码。当然不是在多个地方。

  4. 您确实希望将文件 I/O 隔离到一个位置。

  5. 您希望更喜欢C++"std::string"而不是C样式的"char[]"数组。

  6. 添加了一个示例"尝试/捕获"块

  1. 您实际上并没有在代码中的任何位置调用readFile()。您只需将ave(未初始化)传递给display(),而大多数时间恰好显示为零。

  2. getFileName()的返回值没有分配给任何东西,因此结果被丢弃。

最新更新