雖然我已經使用C#和幾種web-dev語言,但我對C++相當陌生。 我有一個數據庫存儲爲一個.txt文件在一個已知的位置。 .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;
}
我可以對如何進行一些指針。
通過異常,如果您不能打開該文件,並做一些事情(退出的例子) – elyashiv
好第一步是要讀取每個結構的線 - 非常相似,你做了什麼爲計數(說N),但然後你需要循環'N'次,並閱讀3條目,每次... – Caribou
你會想要宣佈一個std :: vector舉行你的鞋。 –