gpt4 book ai didi

c++ - cash reg 将每行中的单个单词加载到不同的结构成员中

转载 作者:太空宇宙 更新时间:2023-11-04 13:24:12 24 4
gpt4 key购买 nike

我的家庭作业让我有点迷茫。我一直在完成这项作业,编写我的代码,删除、重写、重复等。以下是说明:


步骤(1)

与此作业相关联的是一个名为 prices.txt 的数据文件。它包含项目价格的详细信息杂货店。第一列是商品的条形码 ( http://en.wikipedia.org/wiki/Barcode )第二列,从第 11 位开始,是产品名称,第三列,从第 37 位开始,是产品价格。编写一个带有签名 int loadData() 的函数,提示用户输入数据文件的位置在磁盘上,然后将文件中的数据加载到元素数组中。数组的每个元素应该是声明如下的结构:

struct Item {
string code;
string name;
double price;
};

数组本身应该称为项目,并且应该在文件范围内声明如下:

const int MAX_ITEMS = 100;
Item items[MAX_ITEMS];

请注意,数组的大小为 100,因此您可以假设数据文件中的项目数少于 100。

因此,当 loadData 完成将数据加载到数组中时,数组中的某些元素将未被使用。函数 loadData 返回实际加载到数组中的项目数。


我不确定如何尝试使用说明中描述的功能。我的代码:

int loadData () {
string inputFileName;
ifstream inputFile;
int numOfItems = 0;

cout << "Please input the name of the backup file: ";
cin >> inputFileName; //read user input for the location of the
//backup file
inputFile.open(inputFileName.c_str()); //open specified document

if (!inputFile.is_open()) { //If the file does not open the errormsg
cout << "Unable to open input file." << endl;
cout << "Press enter to continue...";
getline(cin, reply);
exit(1);
}
//Not sure where to start. I know I need to get each element from
//each newline.

return numOfItems;
}

我想自己解决这个问题,但这不会发生。因此,如果我能得到一些提示,甚至是建议的知识库,它们会指导我,甚至让我知道从哪里开始。

添加:输入文件:

10001     Apples (bunch)            4.5910002     Bananas (bunch)           4.9910003     Pears (bunch)             5.4920001     White bread (loaf)        2.6920002     Brown bread (loaf)        2.8920003     English Muffins (bag)     3.9930001     Sugar (5 lb bag)          3.9930002     Tea (box)                 4.2930003     Folger's Coffee (Can)     13.29

这是整个输入文件。

最佳答案

由于输入文件似乎使用固定宽度的列,因此提取字段实际上非常容易。就read one line at a time , 并为每一行获取每个元素作为 a sub-string , 并放入结构成员中。还有convert strings to floating-point values的功能

不要担心可能的前导或尾随空格,there are ways of trimming that .

关于c++ - cash reg 将每行中的单个单词加载到不同的结构成员中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33909612/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com