用c++
时间: 2023-07-01 10:24:11 浏览: 50
以下是使用 C++ 实现的程序,满足您的要求:
```c++
#include <iostream>
#include <fstream>
using namespace std;
class FileOpenException: public exception
{
public:
virtual const char* what() const throw()
{
return "无法打开文件!";
}
};
int* read_integers(string filename, int& count)
{
ifstream fin(filename);
if (!fin.is_open())
{
throw FileOpenException();
}
int num;
int size = 10; // 初始化数组大小为10
int* arr = new int[size];
count = 0;
while (fin >> num)
{
if (count == size) // 如果数组已满,动态扩容
{
int* temp = new int[size * 2];
for (int i = 0; i < size; i++)
{
temp[i] = arr[i];
}
delete[] arr;
arr = temp;
size *= 2;
}
arr[count++] = num;
}
fin.close();
return arr;
}
int main()
{
string filename;
cout << "请输入文件名:";
cin >> filename;
int count;
try
{
int* arr = read_integers(filename, count);
double average = 0.0;
for (int i = 0; i < count; i++)
{
average += arr[i];
}
average /= count;
cout << "平均值为:" << average << endl;
delete[] arr;
}
catch (FileOpenException& e)
{
cout << e.what() << endl;
}
return 0;
}
```
程序中定义了一个名为`FileOpenException`的自定义异常类,用于表示文件打开异常。在`read_integers`函数中,程序尝试打开并读取文件中的整数,如果文件不存在或无法打开,则抛出自定义异常类`FileOpenException`。在主函数中,程序先通过`cin`函数获取用户输入的文件名,然后调用`read_integers`函数读取文件中的整数并计算平均值。如果读取文件时出现异常,则会被`try-catch`语句捕获,并在异常处理程序中输出错误信息:"无法打开文件!"。需要注意的是,在`read_integers`函数中动态扩容数组,以便能够读取任意长度的整数序列。在主函数中,使用`delete[]`释放动态分配的数组内存。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)