zoukankan      html  css  js  c++  java
  • ca77a_c++__一个打开并检查文件输入的程序_流对象_操作文件

    /*ca77a_c++__一个打开并检查文件输入的程序

    习题:8.13 8.14
    */

     1 /*ca77a_c++__一个打开并检查文件输入的程序
     2 
     3 习题:8.13  8.14
     4 */
     5 
     6 #include <iostream>
     7 #include <fstream>
     8 #include <string>
     9 #include "get.h"
    10 
    11 using namespace std;
    12 
    13 ifstream& open_file(ifstream &in, const string &file)
    14 {
    15     in.close();
    16     in.clear();//恢复流的状态
    17     in.open(file.c_str());
    18     return in;
    19 
    20 }
    21 
    22 int main()
    23 {
    24     string fileName, s;
    25     cout << "Enter filename:" << endl;
    26     cin >> fileName;
    27     ifstream inFile; //创建流对象inFile
    28     //调用函数打开
    29     if (!open_file(inFile, fileName))
    30     {
    31         cerr << "error: can not open file: " <<fileName<< endl;
    32         return -1;
    33     }
    34     get(inFile);
    35     inFile.close();
    36     return 0;
    37 }

    get.cpp

     1 #include "get.h"
     2 
     3 std::istream& get(std::istream &in)//8.3
     4 {
     5     int ival;
     6     while (in >> ival, !in.eof())//让in.eof()决定是否结束,ctrl+z结束输入
     7     {
     8         if (in.bad())//巨大错误
     9             throw std::runtime_error("IO stream error");
    10         if (in.fail())//判断输入类型是否相同,val是int,如果文件里面是字符,就出错。
    11         {
    12             std::cerr << "bad data,try again." << std::endl; //std名称空间
    13             in.clear();//恢复流到正常状态
    14             in.ignore(200,'
    ');//
    15             continue;
    16         }
    17         std::cout << "输入的数据: " << ival << std::endl;
    18     }
    19     in.clear();//恢复流到正常状态
    20 }

    get.h

     1 //#pragma once
     2 #ifndef _GET_H
     3 #define _GET_H
     4 
     5 //头文件不要用using namesapce std;
     6 #include <iostream>
     7 std::istream& get(std::istream &in);
     8 
     9 
    10 #endif
    欢迎讨论,相互学习。 txwtech@163.com
  • 相关阅读:
    springboot整合mybatisplus
    在layui中使用treetable.js插件
    shiro系列9:基于前端的权限控制和基于后端的权限控制
    springboot文件上传案例
    springboot配置虚拟路径访问上传到磁盘的文件
    springboot文件下载案例
    springboot跨域的处理方式
    springboot上传文件过大的解决方案
    Django与Ajax
    Django查询数据库性能优化
  • 原文地址:https://www.cnblogs.com/txwtech/p/12296882.html
Copyright © 2011-2022 走看看