read在c++中的异常处理

   2024-10-01 4600
核心提示:在C++中,read() 函数通常用于从文件或其他输入流中读取数据以下是一个使用 std::ifstream 和异常处理的示例:#includeiostream#

在C++中,read() 函数通常用于从文件或其他输入流中读取数据

以下是一个使用 std::ifstream 和异常处理的示例:

#include<iostream>#include <fstream>#include<string>int main() {    std::ifstream file("example.txt");    if (!file) {        std::cerr << "Error opening file."<< std::endl;        return 1;    }    std::string line;    try {        while (std::getline(file, line)) {            // Process the line        }    } catch (const std::ios_base::failure& e) {        std::cerr << "I/O error: " << e.what()<< std::endl;        return 1;    } catch (...) {        std::cerr << "Unknown exception caught while reading the file."<< std::endl;        return 1;    }    file.close();    return 0;}

在这个示例中,我们首先检查文件是否成功打开。如果打开失败,我们将输出错误消息并返回非零值。然后,我们使用 try 块来读取文件的每一行。如果在读取过程中发生 I/O 错误,我们将捕获 std::ios_base::failure 异常并输出相应的错误消息。如果捕获到其他类型的异常,我们将输出一个通用的错误消息。最后,我们关闭文件并返回 0。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号