比较和拆分文本文件中的字符串

时间:2016-12-20 00:30:34

标签: c++ text-files ifstream string-comparison

我正在尝试用C ++打开一个文本文件并逐行读取,直到我找到一个特定的字符串,但数据也分成不同的部分......

文本文件如下所示:

entry_one:true,true,false;
entry_two:true,false,false;
entry_three:false,false,false;
entry_four:true,false,true;

我基本上需要将文本文件读入内存,遍历每一行,直到找到具体的“entry _...”我正在寻找,然后我需要将布尔值数据拆分成变量。

到目前为止,我想到了这一点:

ifstream stream;
string line;
stream.open(filepath);
if (stream)
{
    size_t sizepos;
    while (stream.good()){
        getline(stream, line);
    }
}

上面的代码至少会将文本文件打开到内存中以便可以读取,然后getline可以用来读取当前行......

但是我如何检查它是否是我需要的正确条目,然后将真/假拆分成变量?

E.g。在文本文件中找到条目2,并为每个true / false将其放入以下变量

bool bEntryTwo1 = false;
bool bEntryTwo2 = false;
bool bEntryTwo3 = false;

我感到困惑和困惑,是否有人知道他们在做什么来帮助我? thankss! :)

2 个答案:

答案 0 :(得分:3)

我建议将建模文本行作为记录,然后阅读每条记录:

struct Record
{
  std::string name;
  bool        entry1;
  bool        entry2;
  bool        entry3;
};

接下来是添加operator>>来读取数据成员:

struct Record
{
  //...
  friend std::istream& operator>>(std::istream& input, Record& r);
};
std::istream& operator>>(std::istream& input, Record& r)
{
  std::string name;
  std::getline(input, r.name, ',');
  char comma;
  input >> r.entry1 >> comma >> r.entry2 >> comma >> r.entry3;
  return input;
}

然后,您将从文件中读取每条记录,并仅处理您要查找的记录:

Record r;
while (my_data_file >> r)
{
  if (r.name = Name_To_Find)
  {
    Process_Record(r);
    break;
  }
}

阅读记录的好处是,当您找到名称时,您可以获得完整的信息。

另一种方法是将所有记录读入内存(例如std::vector),然后搜索内存以找到它。

有关详细信息,请在Internet上搜索“stackoverflow c ++ read file CSV”。

答案 1 :(得分:0)

对于布尔值,我将使用std::vector<bool>而不是创建单独的布尔值。因此,这是我的问题解决方法。

#include <iostream>
#include <string>
#include <vector>
#include <fstream>


int main()
{
    std::ifstream file("data.txt");
    std::string entry("entry_four");

    std::string line;
    std::vector<bool> boolVals;
    std::string vars;
    while ( std::getline(file, line) ){
         int id(line.find(':'));
         std::string temp(line.substr(0,id));
         if ( entry == temp ){
             vars = line.substr(id+1);
             std::string temp1;

             for ( int i(0); i < vars.size(); ++i ){
                 if ( (vars[i] != ',') && (vars[i] != ';') ){
                     temp1 += vars[i];
                 }else{
                     if ( temp1 == "true" )
                         boolVals.push_back(true);
                     else
                         boolVals.push_back(false);

                    temp1.clear();
                }
            }

         }
    }
    std::cout << vars << std::endl;
    for ( int i(0); i < boolVals.size(); ++i ){
        std::cout << boolVals[i] << " ";
    }
        std::cout << std::endl;


    return 0;
}

对于此条目entry_four:true,false,true;,我们有此输出

true,false,true;
1 0 1

注意:为简单起见,我忽略了代码中的一些细节。例如,您需要仔细检查文件是否已成功打开。我会给你额外的预防措施。

相关问题