实例化对象并保存向量中的项目

Instantiate Object and save items from vector

首先,如果代码草率或错误,我深表歉意。我在使用 C++ 时遇到了困难。

我正在尝试从文件创建客户并将每个客户保存为对象客户并存储每个变量。

我已经成功地打开并读取了将单词保存到矢量的文件。我现在需要创建一个客户并保存信息。

我的问题是 - 既然我有一个包含所有信息的向量,我将如何创建一个新客户并将向量中的第一项存储为 fName,第二项存储为 lName,第三项存储为 acctNumber。向量中的第 4 项是新客户保存为他们的 fName 等等。

我正在使用的文本文件示例如下。
迈克尔杰克逊 1
乔治·琼斯 2
布列塔尼斯皮尔斯 3

目标:以上文件将实例化 3 个客户并设置他们的每个 fName、lName 和 acctNumber 供以后使用。

class CustomerType {
public:
    CustomerType(string f, string l, int a);
    string fName;
    string lName;
    int acctNumber;
    videoType chkdOut;
private:
};

CustomerType::CustomerType(string f, string l, int a) {
    fName = f;
    lName = l;
    acctNumber = a;
}

void createCustomer() {
    vector<string> myVector;
    ifstream myfile;
    myfile.open("custDat.txt");
    if (myfile.is_open())
    {
        while (!myfile.eof())
        {
            string tempString;
            getline(myfile, tempString);
            istringstream iss(tempString);
            string word;

            while (iss >> word) {
                myVector.push_back(word);
            }
        }
        myfile.close();
    }
    else
        cout << "Can't open file" << endl;
}

首先,为您的客户添加一个构造函数 class,它将获取所需的信息:

class customerType {
public:
    customerType( string firstName, string lastName, int accountNumber );
    string fName;
    string lName;
    int acctNumber;
    videoType chkdOut;
private:
};

构造函数将这样定义:

customerType( string firstName, string lastName, int accountNumber )
{
    fName = firstName;
    lName = lastName;
    acctNumber = accountNumber;
}

您必须创建一个方法来将字符串与字符分开,以便从每一行中获取不同的信息:

vector<string> split( string line, char c )
{
    const char *str = line.c_str();

    vector<string> result;

    do
    {
        const char *begin = str;

        while ( *str != c && *str )
            str++;

        result.push_back( string( begin, str ) );
    }
    while ( 0 != *str++ );

    return result;
}

然后,在创建客户的方法中,您可以使用该构造函数创建一个新对象,然后 return 包含客户的向量:

vector<customerType> createCustomer() {

    // create a vector of customers:
    vector<customerType> customers;

    vector<string> myVector;
    ifstream myfile;
    myfile.open("custDat.txt");
    if (myfile.is_open())
    {
        while (!myfile.eof())
        {
            string tempString;
            getline(myfile, tempString);

            // Here you get a vector with each work in the line
            vector<string> splittedString = split(tempString, ' ');

            //Finally here you create a new customer
            customers.push_back(customerType(splittedString[0], splittedString[1], stoi(splittedString[2])));
        }
        myfile.close();
    }
    else
        cout << "Can't open file" << endl;

    return customers;
}

抱歉,我更改了您存储单词的方式。

stoi 函数将字符串转换为整数。