从文件中获取不同类型的项,并将它们添加到数组中
Taking Items of varying types from file and adding them to an array
我目前正在一个实验室工作,该实验室需要以各种方式为硬件商店保留库存。其中一种方法是将信息放入一个数组中。有一个工具列表,每个工具都有一个记录编号、名称、数量和成本。我认为最好的方法是将信息放入一个文本文件中,然后从那里将其添加到数组中,但我一直纠结于如何做到这一点。到目前为止,我可以手动添加每个项目,但这非常乏味,不容易处理。
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++的新手,这正是我首先想到的。
非常感谢您的帮助。谢谢
我认为您希望将文本文件中的值存储到数组中。如果是,您可能希望从读取文件中的每一行开始。接下来,将行拆分为每个数据字段。然后追加到文本文件并重复。
为了阅读每一行,我用一根绳子固定正在阅读的行接下来,每次看到角色时都会拆分该行。我用了一个";"以分隔值。例如,文件的第一行应该是:
68;Screwdriver;106;6.99
然后,拆分过程返回一个字符串向量。按顺序如下:记录编号、名称、数量和价格。整数和双精度的数字需要从字符串中转换,因此有两个函数投射它们。最后,将这些值存储在指定的索引中。例如,在程序运行后,数组的索引68将保持68,Screwdriver,1066.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();
}
相关文章:
- C++向数组添加元素并调整数组大小
- 向对象数组 c++ 添加值
- 在 c++ 中将 Char 数组添加到 Char * 变量
- 向动态数组添加内容
- 动态数组添加元素而不创建结构变量/对象
- 将 2D 数组添加到 1D 数组
- 如何使用sprintf将UINT_64的数组添加到一个字符数组中
- 当循环崩溃时,不向数组添加单词
- 如何将对象数组添加到另一个类
- 将字符数组添加到 const string&in C++
- 如何将数组添加到列表中
- 向量数组C++ - 添加元素时的奇怪行为
- 将char数组添加到C 中的字符串
- strncpy向我的char数组添加了额外的字符
- 在C++中向数组添加项的最有效方法
- 将类对象的数组添加到一个主类对象中
- 将BSON数组添加到MongoDB 3.2文档并提取值(MongoCXX 3.2)(C++11)
- 我是否正确地为 2D 数组添加了行与列
- 读取文件内容,存储在数组中,向数组添加更多内容,然后将新数组存储在文件C++中
- C++类对象数组 - 添加新记录