0

尽管我曾短暂地使用过 C# 和一些 Web 开发语言,但我对 C++ 还是很陌生。我有一个以 .txt 文件形式存储在已知位置的数据库。.txt 文件的第一行是数据库中有多少项目。我有一个结构来读取所有值,因为它们的格式相同。

我已经设法编写了一段代码,它将读入文件并给我一个整数值,表示有多少项目,我只需要帮助将数据读入结构数组。

一个示例数据库是

3

NIKEAIRS
9
36.99

CONVERSE
12
35.20

GIFT
100
0.1

我的结构是

struct Shoes{
   char Name[25];
   unsigned int Stock;
   double Price;
};

我读取项目数量的代码是

#include <iostream>
#include <fstream>
#include <string>
using namespace std;


int main ()
{
    char UserInput;

    string NumOfItems; //this will contain the data read from the file
    ifstream Database("database.txt"); //opening the file.
    if (Database.is_open()) //if the file is open
    {
        int numlines;
        getline (Database,NumOfItems);
        numlines=atoi(NumOfItems.c_str());
        cout<<numlines;
    }
    else cout << "Unable to open file"; //if the file is not open output
    cin>>UserInput;
    return 0;
}

我可以就如何进行一些指示。

4

2 回答 2

2

这样的事情怎么样?我知道有更有效的方法可以做到这一点,但至少这应该让你朝着正确的方向开始。干杯!

#include <iostream>
#include <fstream>
#include <string>

#include <vector>
#include <stdlib.h>

using namespace std;

struct Shoes {
    char Name[25];
    unsigned int Stock;
    double Price;
};

vector<Shoes> ShoeList;

static Shoes readShoe(std::ifstream& fs)
{
    char buffer[200];               //  temporary buffer
    Shoes s;

    fs.getline(buffer, sizeof(buffer));     // newline
    fs.getline(s.Name, sizeof(buffer));     // name
    fs.getline(buffer, sizeof(buffer));     // amt in stock
    s.Stock=atoi(buffer);
    fs.getline(buffer, sizeof(buffer));     // price
    s.Price=strtod(buffer, 0);

    return s;
}

int main ()
{
    char UserInput;

    string NumOfItems; //this will contain the data read from the file
    ifstream Database("database.txt"); //opening the file.
    if (Database.is_open()) //if the file is open
    {
        int numlines;
        getline (Database,NumOfItems);
        numlines=atoi(NumOfItems.c_str());
        cout<<numlines;

    cout << endl;
    for(int i=0; i < numlines; ++i)
    {
        Shoes s = readShoe(Database);
        ShoeList.push_back(s);
        cout << "Added (Name=" << s.Name << "," << s.Stock << "," << s.Price << ") to list." << endl;
    }

    }
    else cout << "Unable to open file"; //if the file is not open output

    cin>>UserInput;

    return 0;
}
于 2012-11-11T16:36:48.357 回答
0
for (int i = 0; i < numlines; ++i)
{
 Shoes sh();
 Database >> sh.Name >> sh.Stock >> sh.price;
 //do something with sh (add it to a list or a array for example
}
于 2012-11-11T16:12:41.617 回答