我对C ++很陌生,尽管我曾经简单地使用过C#和一些web-dev语言。 我有一个数据库存储为已知位置的.txt文件。 .txt文件的第一行是数据库中有多少项。 我有一个Struct来读取所有值,因为它们具有相同的格式。
我已经设法编写了一段代码,它将在文件中读取并给出一个有多少项的整数值,我只需要帮助将数据读入一个结构数组。
示例数据库是
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;
}
我是否可以提供一些有关如何继续的建议。
答案 0 :(得分: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;
}
答案 1 :(得分: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
}