简体   繁体   English

C ++从csv文件读取,然后将数据分配给类成员

[英]C++ read from a csv file and then assign the data to class member

I am a C++ beginner. 我是C ++初学者。 My basic code shown below is able to read csv file and print out data line by line. 我下面显示的基本代码能够读取csv文件并逐行打印出数据。 However, I cannot figure out how to assign all these data to my defined commuter class variables. 但是,我无法弄清楚如何将所有这些数据分配给定义的通勤类变量。 I have tried alot of online tutorial but it will always show errors that I am not sure how to debug.Could anyone give me a hand or some hints? 我已经尝试了很多在线教程,但它总是会显示我不确定如何调试的错误。有人可以帮我一些忙吗? thank you. 谢谢。

sample data: 样本数据:

commuter1;A;7;20 
commuter2;B;8;30
commuter3;F;10;10
.....
#include<iostream>
#include<string>
#include<vector>
#include<fstream>//strtok 
using namespace std;
class Commuter {
private:
    string name;
    char point;
    int hour;
    int minute;
public:
    Commuter(string name, char point, int hour, int min) {
        this->name = name;
        this->point = point;
        this->hour = hour;
        this->minute = min;
}
void setname(string name);
void setpoint(char point);
void sethour(int hour);
void setmin(int min);
vector<Commuter> commuter;
};

void Commuter::setname(string name) {
this->name = name;
}
void Commuter::setpoint(char point) {
this->point = point;
}
void Commuter::sethour(int hour) {
this->hour = hour;
}
void Commuter::setmin(int min) {
this->minute = min;
}
int main() {
ifstream commuterfile;
string filename;
string str;
cout << "Enter the file path: " << endl;
cin >> filename;
commuterfile.open(filename.c_str());
if (!commuterfile) {
    cerr << "ERROR" << endl;
    exit(1);
}
while (getline(commuterfile, str, ';')) {
    cout << str << endl;
}
commuterfile.close();
return 0;
}

You have the line of data in your str variable, so you should be able to take a few more steps and add that to your class. 您的str变量中有一行数据,因此您应该能够再执行几步并将其添加到类中。

First, you should figure out how to split the string into components . 首先,您应该弄清楚如何将字符串拆分为components

The next step is to convert each component from a string to the data type you need. 下一步是将每个组件从字符串转换为所需的数据类型。 atoi will be a good function for converting string to int. atoi将是将字符串转换为int的好函数。

You need an instance of your class as well. 您还需要一个类的实例。 Eg Commuter commuter; 例如Commuter commuter; Then you can call the functions on the instance like commuter.setXXX(variable); 然后,您可以在实例上调用commuter.setXXX(variable);等函数commuter.setXXX(variable);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM