读取Excel文件以构造C ++

问题描述

我想在结构中读取一个excel文件,但问题是它将excel列读为整行。我需要这些数据一一列。使用fstreams我打开了一个包含许多列的文件

enter image description here

我以我所拥有的知识尝试过它,但是它显示了所有详细信息,如我在下面显示的那样

Name :      Name,Nick
Nick :   name,Phone
Phone :  number,Carrier,Address
Carrier :   Yashodhara,Yash,711256677,Mobitel,"No.
Address : 29,Bollatha,Ganemulla"
-----------------------
Name :      Madushani,Madu,711345678,"No.
Nick :   12,Phone :  Gampaha"
Carrier :   Sadeepa,Sad,789002264,Hutch,"No.
Address : 123,-----------------------

我用以下代码尝试了此操作。

#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>

using namespace std;

//structure for store contact details
struct contacts {
    string name;
    string nickName;
    string phoneNumber;
    string carrier;
    string address;
};




int main() {
    
    const int LIMIT = 10;
    contacts limit[LIMIT];
    ifstream file;
    file.open("Contact.csv");

    if (file) {
        while (!(file.eof())) {
            for (int i = 0; i <= 7; i++) {
                file >> limit[i].name;
                file >> limit[i].nickName;
                file >> limit[i].phoneNumber;
                file >> limit[i].carrier;
                file >> limit[i].address;
                
            }
        }
    }
    else {
        cout << "Error";
    }

    // Using the following to debug output
    for (int i = 0; i < 7; i++) {
        cout << "Name :      " << limit[i].name << endl
            << "Nick :   " << limit[i].nickName << endl
            << "Phone :  " << limit[i].phoneNumber << endl
            << "Carrier :   " << limit[i].carrier << endl
            << "Address : "  << limit[i].address << endl
            << "-----------------------" << endl;
    }


    return 0;
}

我想知道如何以适当的顺序将以上细节读入结构。

解决方法

您可以使用std::getline()

string readString;
if (file) {

    while (!(file.eof())) {
        getline(file,readString); // Read the column headers
        for (int i = 0; i <= 7; i++) {
            getline(file,limit[i].name,','); // ',' is the separator
            getline(file,limit[i].nickName,');
            getline(file,limit[i].phoneNumber,limit[i].carrier,limit[i].address); // Read until the end of the line
            
        }
    }
}

我不得不提到我没有对其进行测试,因此可能需要一些安排。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...