C ++读取分隔文件并创建对象

时间:2014-12-05 11:14:23

标签: c++

我正在尝试读取一个文件,逐行使用数据创建一个对象。

我当前的文件是这样的,读取文件的代码将在下面找到。

*   1223 Fake1 Name1  60  70  80  24 89  add1  Male
    1224 Fake2 Name2  61  70  81  80 24  add2  Male
    1225 Fake3 Name3  63  70  82  80 89  add3  Male
    1226 Fake4 Name4  63  70  83  80 88  add4  Male*

我遇到的问题是我需要在文件中放置分隔符,以便一个人可以拥有多个名称,并且地址现在可以包含多个字符串,直到分隔符。

我想将我的文件更改为此内容;

   *1223 : Fa1 Name1 : 60 : 70 : 80 : 24 :89 : This will be address1 : Male 
    1224 : Fake2 Name2 : 61 : 70 : 81 : 80 :24 : This will be address2 : Male
    1225 : Fake3 Name3 : 63 : 70 : 82 : 80 :89 : This will be address3 : Male
    1226 : Fake4 Name4 : 63 : 70 : 83 : 80 :88 : This will be address4 : Male*

如何更新下面的代码,以便它可以使用分隔符来创建对象?

void loadFile(Person people[], int* i)
{
    ifstream infile("people2.txt");

    if ( !infile.is_open()) {
      // The file could not be opened
        cout << "Error";
    }
    else
    {
        string str, str1, str2, str3, str4;
        int x[6];
        while(!infile.eof())
        {
            infile >> str1; 

            infile >> str2; 

            inile >> str; 
            x[0] = stoi(str);

            infile >> str; 
            x[1] = stoi(str);

            infile >> str; 
            x[2] = stoi(str);

            infile >> str; 
            x[3] = stoi(str);

            infile >> str; 
            x[4] = stoi(str);

            infile >> str; 
            x[5] = stoi(str);
            infile >> str3; 
            infile >> str4;             
            people[*i] = Person( x[0], str2 + " " + str1, x[1], x[2], x[3], x[4], x[5], str3, str4);
            (*i)++;
        }
        infile.close();
    }

}

1 个答案:

答案 0 :(得分:0)

您可以使用std :: getline逐行读取文件,也可以根据指定的分隔符拆分字符串。例如:

#include <string>
#include <fstream>
#include <sstream>
#include <vector>


int main() {
  std::ifstream infile("people2.txt");
  if (!infile) {
    std::cerr << "Could not open file." << std::endl;
    return 1;
  }

  std::string line;
  while (std::getline(infile, line)) {  // Read file line by line.
    std::string field;
    std::vector<std::string> separated_fields;
    std::istringstream iss_line(line);
    while (std::getline(iss_line, field, ':')) { // Split line on the ':' character
      separated_fields.push_back(field);    // Vector containing each field, i.e. name, address...
    }
    // Do something with the results
    separated_fields[0]; // ID
    separated_fields[1]; // Names
    separated_fields[2]; // Number
    separated_fields[3]; // Number
    separated_fields[4]; // Number
    separated_fields[5]; // Number
    separated_fields[6]; // Number
    separated_fields[7]; // Address
    separated_fields[6]; // Sex 
  }
}

然后,您可以在标记为// Do something with the results的部分中创建对象,方法是在示例中传递单个字符串,或者将向量传递给构造函数并处理每个字段。