首页 > 解决方案 > 从文件中获取不同类型的项目并将它们添加到数组中

问题描述

我目前正在一个实验室工作,该实验室需要以各种方式为五金店保留库存。其中一种方法是将信息放入数组中。有一个工具列表,每个工具都有一个记录号、名称、数量和成本。我认为执行此操作的最佳方法是将信息放入文本文件并从那里将其添加到数组中,但我一直不知道该怎么做。到目前为止,我可以手动添加每个项目,但这非常乏味并且不容易使用。

struct node {
    int recordNum; 
    char toolName[20]; 
    int quantity; 
    double toolCost; 

    node* next; 
};

void unsortedArray() {
    ifstream toolsFile("Tools.txt");
    const int MAX = 100;
    node unsortedArr[MAX];

    unsortedArr[0].recordNum = 68;
    strcpy_s(unsortedArr[0].toolName, "Screwdriver");
    unsortedArr[0].quantity = 106;
    unsortedArr[0].toolCost = 6.99;
}

我使用的是结构节点,因为我以后必须使用链表。这是包含每种产品信息的 .txt 文件。

68  Screwdriver     106     6.99
17  Hammer          76      11.99
56  Power saw       18      99.99
3   Electric Sander 7       57
83  Wrench          34      7.5
24  Jig Saw         21      11
39  Lawn mower      3       79.5
77  Sledge hammer   11      21.5

如果有一种方法可以做到这一点,它不涉及也可以正常工作的文本文件。我是 C++ 新手,这正是我首先想到的。

任何帮助深表感谢。谢谢!

标签: c++arrays

解决方案


我收集到您想将文本文件中的值存储到数组中。如果是这样,您可能希望从读取文件中的每一行开始。接下来,将该行拆分为每个数据字段。然后附加到文本文件并重复。

为了读取每一行,我使用一个字符串来保存正在读取的行 接下来,每次看到一个字符时都会拆分该行。我用了一个';' 分隔值。例如,文件的第一行将显示:

68;Screwdriver;106;6.99

然后拆分过程返回一个字符串向量。这按顺序排列:记录编号、名称、数量和价格。整数和双精度数需要从字符串转换,因此有两个函数对它们进行转换。最后,这些值存储在指定的索引中。例如,在程序运行后,数组的索引 68 将保存 68,Screwdriver, 106, 6.99。

这是工作解决方案

注意,为了简化存储方法,我将工具名称更改为字符串。如果需要,请随时将其更改回来

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>

std::vector<std::string> split(std::string strToSplit, char delimeter) {
    std::stringstream ss(strToSplit);
    std::string item;
    std::vector<std::string> splittedStrings;
    while (std::getline(ss, item, delimeter)) {
        splittedStrings.push_back(item);
    }
    return splittedStrings;
}

struct node {
    int recordNum;
    std::string toolName; // Changed this as string was already used elsewhere
    int quantity;
    double toolCost;

    node* next;
};


int main() {
    node node_array[100];
    int index;

    std::ifstream tool_file;
    tool_file.open("Text.txt"); //The record file

    std::string line;
    std::vector<std::string> split_line;

    while (std::getline(tool_file, line)) { //Repeat for each line of file

        split_line = split(line, ';'); // Split each line into its components
        index = stoi(split_line[0]); // Convert record num into an int

        node_array[index].toolName = split_line[1];  // Save values into index
        node_array[index].quantity = stoi(split_line[2]);
        node_array[index].toolCost = stod(split_line[3]);
        
    }
    tool_file.close();
    
}

                   

推荐阅读