读取制表符分隔的文本文件,其中某些行没有列

时间:2019-03-02 22:36:16

标签: c++

我正在尝试将我的文本文件读入我制作的类对象的向量中:

cust_id first_name  last_name   company_name    address city    state   zip
101 James   Butler      6649 N Blue Gum St  New Orleans LA  70116
102 Josephine   Darakjy Chanay, Jeffrey A Esq   4 B Blue Ridge Blvd Brighton    MI  48116
103 Art Venere      8 W Cerritos Ave #54    Bridgeport  NJ  08014
104 Lenna   Paprocki    Feltz Printing  639 Main St Anchorage   AK  99501
……...

如您所见,company字段的列包含几个空字段,因此我的向量包含很多零。不确定如何执行此操作。我已经检查了我们的社区,但没有发现任何东西。如果有人可以快速浏览一下C ++,那么我对C ++还是陌生的。谢谢。提示也可以。

/*********My attempt*****************/
vector<class_a> load_vector() {
string file_name = "abc.txt";
ifstream input_file(file_name, ios::in);
vector<class_a> c_vector;
int id;
string f_name;
string l_name;
string comp_name;
string address;
string city;
string state;
int postal_code;

if (input_file) {
    string line;
    class_a c_info;
            /*Ignores the header*/
    input_file.ignore(numeric_limits<streamsize>::max(), '\n');
    while (getline(input_file, line, '\t')) {
        stringstream ss(line);
        ss >> id >> f_name >> l_name >>
            comp_name >> address >> city >>
            state >> postal_code;

        c_info.set_id(id);
        c_info.set_first_name(f_name);
        c_info.set_last_name(l_name);
        c_info.set_company(comp_name);
        c_info.set_address(address);
        c_info.set_city(city);
        c_info.set_state(state);
        c_info.set_postal_code(postal_code);

        c_vector.push_back(c_info);
    }
}
else {
    cout << "Text file is missing, place the text file in the folder.\n";
    exit(0);
}
input_file.close();
return c_vector;

}

0 个答案:

没有答案