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();



}

これは、このテキストファイルを構造体の配列に読み込もうとしている私のコードです。ただし、各ユーザーのユーザー名をカウントしようとすると、機能しません。テキスト ファイルの最初の 8 行を出力するだけです。これを修正して、構造体配列にテキストを入力し、8 人の各ユーザーのユーザー名だけを出力するにはどうすればよいですか?

前もって感謝します!

4

2 に答える 2

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++;
}
于 2013-03-10T07:32:38.427 に答える
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();

これらのエラーが発生した理由は、行の準備が1回しかなかったため、、、の値がusername、 getlineの実行時に保存されたfirstnamelastnamefavTVshow同じ値に割り当てられていたためです。

私は以下を提案します(これはCの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;

このようにして、4行が正常に読み取られ(構造体の要素数)、それぞれに値が割り当てられ、構造体の配列の各要素に適切に割り当てることができるようになります。

さて、理想的には、これはそれを行うための最良の方法ではありません-ベクトルなどを使用することもできますが、問題セットから、私はそれを同じ形式に保ちました。

于 2013-03-10T07:34:27.657 に答える