2013-03-10 74 views
1
`#include <iostream> 
#include <fstream> 

using namespace std; 


// user struct 
struct userInfo { 
    string username; 
    string firstName; 
    string lastName; 
    string favTVshow; 

}; 

// create text file with each person's information 
void dataBase(){ 
    ofstream dataFile("db.txt"); 

dataFile << "8\ngboss\nGriffin\nBoss\nHow I Met Your Mother\nechill\nEdwina\nCarol\nGossip Girl\nestone\nEmma\nStone\nScrubs\njcasablancas\nJulian\nCasablancas\nLost\nrobflew\nRob\nFlewelling\nWorkaholics\ncwoodsum\nCam\nWoodsum\nGlee\nrydogfav\nRyan\nFavero\nHomeland\nfishmans\nSam\nFishman\nEntourage\n"; 

    dataFile.close(); 
} 

// read in database text file to an array 
void dataBase_toArray(){ 
    userInfo userArray[8] 
    string line; 
    int loop = 0; 

ifstream dataFile("db.txt"); 

if (dataFile.is_open()){ 
    while (getline(dataFile,line)) 
    { 
     userArray[loop].username = line; 
     userArray[loop].firstName = line; 
     userArray[loop].lastName = line; 
     userArray[loop].favTVshow = line; 
     cout << userArray[loop].username << endl; 
     loop++; 
    } 
    dataFile.close(); 
} 
else cout << "Can't open file" << endl; 

} 

// main function 
int main() { 

userInfo userArray[8]; 

dataBase(); 
dataBase_toArray(); 



} 

所以這是我的代碼我想在這個文本文件中讀入一個struct數組。但是,當我嘗試關閉每個用戶的用戶名時,它不起作用。它只是打印出我的文本文件的前8行。我怎樣才能解決這個問題,並讓它輸入文本到struct數組並輸出8個用戶中每個用戶的用戶名?讀取文本文件到一個結構數組

在此先感謝!

回答

0

你的問題就在這裏:

while (getline(dataFile,line)) 
{ 
    userArray[loop].username = line; 
    userArray[loop].firstName = line; 
    userArray[loop].lastName = line; 
    userArray[loop].favTVshow = line; 
    cout << userArray[loop].username << endl; 
    loop++; 
} 
dataFile.close(); 

你得到這些錯誤的原因是那你只准備好一行,因此username,firstname,lastnamefavTVshow的值被分配到相同的值,即s當getline運行時變成紅色。

我提出以下(這是一個有點讓人想起C'S的fscanf的):

while (getline(dataFile,line1) && getline(dataFile, line2) && getline(dataFile, line3) && getline(dataFile, line4)) 
{ 
    userArray[loop].username = line1; 
    userArray[loop].firstName = line2; 
    userArray[loop].lastName = line3; 
    userArray[loop].favTVshow = line4; 
    ++loop; 
} 

其中:

string line; 

已經換成這樣:

string line1, line2, line3, line4; 

這方式,它確保,四行是成功讀取(這是結構中元素的數量),並且每個元素都被賦值,現在可以將正確分配給給結構數組中的每個元素。

現在,理想情況下,這不是最好的方法 - 你可以使用矢量和類似,但從你的問題集,我保持它在相同的格式。

+0

謝謝,這很有道理! – user22 2013-03-10 07:52:25

+0

不客氣! ;) – jrd1 2013-03-10 07:52:57

0

我認爲第一行的文件中(「8」)是用戶數:

int n; 
dataFile >> n; 
for (int i = 0; i < n; ++i) 
{ 
    getline(dataFile,line); 
    userArray[loop].username = line; 
    getline(dataFile,line); 
    userArray[loop].firstName = line; 
    getline(dataFile,line); 
    userArray[loop].lastName = line; 
    getline(dataFile,line); 
    userArray[loop].favTVshow = line; 
    cout << userArray[loop].username << endl; 
    loop++; 
} 
相關問題