C ++-需要读取存储在文件(.txt)中的时间戳并正确检索

时间:2018-07-16 15:37:00

标签: c++ c++11

我有一种方案,可以在文件(.txt)中存储五个不同的日期和时间戳,并检索它们并将其映射到不同的变量进行处理。

例如,我有以下数据需要写入文件中。

2018-07-16 12:32:12
2018-07-16 12:31:17
2018-07-16 12:30:45

在我的应用程序中,我需要从文件中检索它并将其映射到三个不同的变量以进行如下处理,

std:: string var1 = 2018-07-16 12:32:12;
std::string var2 = 2018-07-16 12:31:17;
std::string var3 = 2018-07-16 12:30:45;

我可以使用以下代码读取和写入单行变量,

    void readFromFile(std::string& var)
    {
      std::fstream file(fileName_str, std::fstream::in | std::fstream::out | 
                                                       std::fstream::app );
      if( ! file ) {
        cout << "Unable to open file:" << fileName_str << ";
        return;
     }
     std::string line;
     if (std::getline(file, line)) {           
       var = line;
     }
     file.close();
  }

void writeToFile(std::string& timeString)
{
 if( fileName_str.empty() ) {
   cout << "File name is empty so returning from it.";
   return; 
 }
 std::ofstream file(fileName_str);
 if( ! file ) {
    cout << "Unable to open file:" << fileName_str << ", continuing WITHOUT using it.";
    return;
 }
 file << timeString;
 file.close();
}
}

但是需要帮助来对三个不同的变量进行相同操作。任何实现它的建议。

1 个答案:

答案 0 :(得分:2)

执行此操作的一个好方法是使用std :: getline,但不止一次。假设您的文件中有三行。您可以这样阅读这些行:

#include <vector>

void readFromFile(std::vector<std::string>& vector_of_lines)
{
  std::fstream file(fileName_str, std::fstream::in | std::fstream::out | 
                                                   std::fstream::app );
     if (!file) {
         cout << "Unable to open file:" << fileName_str << std::endl;
         return;
     }
     std::string line;
     while (std::getline(file, line)) {           
         vector_of_lines.push_back(line);
     }
     file.close();
 }

这应该为您提供一个矢量,其中包含文件中的行。

然后,如果要将这些检索到的值存储在变量中,则将调用如下代码:

std::vector<std::string> myvec;
readFromFile(myvec);

std::string str1 = myvec[0];
std::string str2 = myvec[1];
std::string str3 = myvec[2];

您还可以选择根本不将myvec转移到其他变量中,而是暂时使用myvec来存储它们。但是,如果您必须将它们存储在其他位置,那么您将采用这种方式。