大家好,并提前为Newbie问题而感到同意,但我没有发现任何特定于我的问题的主题。我有一个产品的文本文件,如下所示:
//不。//说明//价格
100 Office_seat 102.99
200台224.99
300 Computer_desk 45.49
400 desk_lamb 23.99
500书架89.49
我想阅读它并将其保存在一个数组中,我将稍后搜索product_pin并计算客户购买的总价格。
尝试了类似于我发布的代码之类的东西,但我认为我启动了这一切都错了。我将不胜感激。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream file("Proionta.txt");
if(file.is_open())
{
string myArray[15];
for(int i=0;i<15;i++)
{
file>>myArray[i];
}
}
system ("pause");
}
我应该尝试制作一个函数以将代码放入其中吗?
让我们从记录建模概念开始,然后获得原始。
您要 model 文本行作为记录:
struct Record
{
unsigned int number;
std::string description;
double price;
};
下一步将是Record
的过载operator>>
:
struct Record
{
unsigned int number;
std::string description;
double price;
friend std::istream& operator>>(std::istream& input, Record& r);
};
std::istream& operator>>(std::istream& input, Record& r)
{
input >> r.number >> r.description >> r.price;
return input;
}
使用上述代码,您可以在文件中读取:
std::vector<Record> database;
Record r;
while (my_text_file >> r)
{
database.push_back(r);
}
编辑1:没有struct
假设您不知道如何使用class
或struct
。
每个字段都可以单独读取:
unsigned int number;
std::string description;
double price;
while (my_text_file >> number >> description >> price)
{
// Do something with number, description, price
}
编辑2:数组与Vector
许多作业要求您对数据进行一些操作,例如平均值或搜索。这通常需要您保存数据。
两个流行的容器(从学生的角度来看)是数组和std::vector
。
数组不是一个不错的选择,因为使用文件I/O,您永远不确定有多少记录,并且数组喜欢静态(永不更改)。因此,您需要自己进行调整大小:
static const unsigned int initial_capacity = 16U;
Record database[initial_capacity];
unsigned int capacity = initial_capacity;
Record r;
unsigned int items_read = 0;
while (my_text_file >> r)
{
if (items_read < capacity)
{
database[items_read] = r;
++items_read;
}
else
{
// Allocate new, larger array
// Copy items from old array to larger array.
// Update capacity variable.
// Delete old array
// Change database pointer to new array
}
}
std::vector
的一个不错的功能是您可以像数组一样访问它,并且它将根据需要自动增加容量。