如何解决读取Excel文件以构造C ++
我想在结构中读取一个excel文件,但问题是它将excel列读为整行。我需要这些数据一一列。使用fstreams我打开了一个包含许多列的文件
我以我所拥有的知识尝试过它,但是它显示了所有详细信息,如我在下面显示的那样
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
}
}
}
我不得不提到我没有对其进行测试,因此可能需要一些安排。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。