2012-11-11 73 views
0

雖然我已經使用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; 
} 

我可以對如何進行一些指針。

+0

通過異常,如果您不能打開該文件,並做一些事情(退出的例子) – elyashiv

+0

好第一步是要讀取每個結構的線 - 非常相似,你做了什麼爲計數(說N),但然後你需要循環'N'次,並閱讀3條目,每次... – Caribou

+1

你會想要宣佈一個std :: vector 舉行你的鞋。 –

回答

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 
} 
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; 
} 
+0

謝謝我會試試這個,你可能知道一個解決方案,不使用向量,因爲我試圖只用我原來的代碼中的3個庫來實現這一點。 –

+0

@JimBob標題不是庫。 '#include '不需要鏈接任何附加庫。但是,如果你真的摔倒了,你需要在沒有矢量的情況下做到這一點,你仍然可以使用c風格的數組''ShoeList = new Shoes [numlines]; ... ShoeList [i] = s; ...刪除[] ShoeList;'但運氣好,在腳下射擊自己。使用std :: vector! – kakTuZ