2013-03-10 103 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++; 
}