【问题标题】:How to effectively and correctly read input from a file in c++?如何有效且正确地从 C++ 文件中读取输入?
【发布时间】:2018-05-26 23:25:38
【问题描述】:

我有一个程序,我需要一个选项来将有关事件的信息导入日历。当事件被导出时,每条信息都有自己的一行,所以我使用 >> 运算符(对于 int 类型)和 getline(对于字符串)的组合。 有一个更好的方法吗?如此多的仅用于输入读取的代码行似乎有点杂乱无章,也许这也不是解决此问题的最安全方法。有没有人建议任何改进?另外,之后关闭文件更好还是自动完成?

bool importFunction(const string &file, const Calendar &cal) {
  ifstream reader;
  reader.open(file);
  string type, description, country, city, street;
  int day, month, year, fHour, fMinute, fSecond, tHour, tMinute, tSecond, 
  number_street;

  if(reader.is_open()){
  getline(reader, type);
  getline(reader, description);
  reader >> day >> month >> year >> fHour >> fMinute >> fSecond >> tHour >> 
  tMinute >> tSecond;
  reader.ignore();//ignore trailing newline
  getline(reader, country);
  getline(reader, city);
  getline(reader, street);
  reader >> number_street;

  if(type=="long") {
  LongEvent event(description, Date(day, month, year), Time(fHour, fMinute, 
  fSecond), Time(tHour, tMinute, tSecond), Location(country, city, street, 
  number_street));

  cal.addEvent(event);
  }
  else if(type=="short") {
  ShortEvent event(description, Date(day, month, year), Time(fHour, fMinute, 
  fSecond), Time(tHour, tMinute, tSecond), Location(country, city, street, 
  number_street));

  cal.addEvent(event); 
  }


  else cout << "FILE WAS NOT OPENED" << endl;


}

【问题讨论】:

  • 一些小的改进可能是可能的,但如果你的数据格式那么复杂,你的阅读器功能也必须那么复杂。
  • 您对安全有任何具体的担忧吗?否则,老实说,我真的看不到重大改进,也许其他人会。每个阅读操作似乎都有不同的目的,所以我认为你无能为力。代码大部分都很简洁——除了最后的对象构造。

标签: c++ input ifstream


【解决方案1】:

我建议为输入数据集创建一个类,并创建一个处理输入操作的成员函数,无论是来自文件还是任何其他来源。

这项改进只会使您的代码更具可读性、可理解性和面向对象的编程。

但是我可以看到你的代码很好。

【讨论】:

    【解决方案2】:

    您可以使用 time_t(新编译器上的 64 位整数)将日期/时间值存储为单个值。与time_t 和您的Calendar 结构相互转换。代码不一定会更短,但文件会更小,因为它只包含一个值。

    #include <iostream>
    #include <ctime> 
    #include <fstream>  
    
    int main()
    {
        struct tm timeinfo = { 0 };
        timeinfo.tm_year = 2018 - 1900;
        timeinfo.tm_mon = 0;//<- January
        timeinfo.tm_mday = 1;//<- first
        timeinfo.tm_hour = 1;
        timeinfo.tm_min = 1;
        timeinfo.tm_sec = 1;
        time_t rawtime = mktime(&timeinfo);
    
        std::ofstream fout("file.txt");
        fout << rawtime;
        fout.close();
    
        std::ifstream fin("file.txt");
        rawtime = 0;
        fin >> rawtime;
    
        struct tm *readtime = localtime(&rawtime);
    
        char buf[100];
        strftime(buf, sizeof(buf), "%c\n", readtime);
        std::cout << buf;
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-07
      • 2012-01-24
      • 2021-09-01
      • 2016-02-26
      • 2022-01-01
      • 2012-02-21
      • 2011-01-30
      • 2015-03-31
      相关资源
      最近更新 更多