2016-07-18 13 views
0

txtファイルから構造体の配列にデータを読み込む関数を作成するには、いくつかの助けが必要です。 データをアレイリストに保存しようとしています。 names.txtファイル全体を読み込み、各行のデータをName型の構造体に格納するには、関数loadNamesを呼び出す必要があります。 main関数は、この配列の最初の要素の構造体に行のデータを読み込み、2行目のデータを2番目の要素に読み込むなど、Name構造体の配列をloadNamesに渡す必要があります。 names.txtファイルのすべての4429行loadNamesが完了してmainに戻った後、ファイルnames.txtは、このアプリケーションの実行中に再び読み取られてはなりません。次のように構造体の配列にテキストファイルを格納する

#include <iostream> 
#include <iomanip> 
#include <fstream> 
using namespace std; 
const int SIZE=4429; 
const int NAME_LEN=21; 
const int NUM_RANKS=11; 
//Structure used to store the data contained on one line of the file. 
//name is an array of strings. 
//rank is an array of int storing 
struct Name{ 
    char name[21]; 
    int rank[11]; 
}; 
void loadNames(Name []); 

int main(){ 
    Name list[SIZE]; 
    char choice; 
    loadNames(list); 

    return 0; 
} 
//The function that has been kicking my ass I tried using a loop 
//to populate the array but I'm unable to separate the strings and the  numbers 
void loadNames(Name list[]){ 
    ifstream nameList; 
    int count=0; 
    char line[4430]; 
    int ch; 
    nameList.open("names.txt"); 
    while((ch=nameList.peek())!=EOF){ 
     nameList.getline(line,SIZE); // I was trying a [for] loop but I am   
             // not sure if it should replace the [while] loop. 
    }; 
    nameList.close(); 
} 

txtファイルは、(それはだが長くなり、ですが、それは

A 83 140 228 286 426 612 486 577 836 0 0 
Aaliyah 0 0 0 0 0 0 0 0 0 380 215 
Aaron 193 208 218 274 279 232 132 36 32 31 41 
Abagail 0 0 0 0 0 0 0 0 0 0 958 
+2

にデータを分離.... –

+0

を持ちます〜によって11列のint – Francisco

+1

名前にスペースがありますか?デリミタとは何ですか?あなたの質問に使用されている実際のファイルの2行を編集してください。 –

答えて

0

同じフォーマットに従うだから私は配列にファイルからデータを保存することができたが、今、私はよ続い名前で始まるそれぞれが、それは周りの4429行のリストだトラブル我々はnames.txtファイルの内容が何であったか知っていた場合、それが役立つだろう名前と番号

void loadNames(Name list[]){ 
    int count=0; 
    int ch; 
    char line[SIZE]; 
    int lineNumber[SIZE]; 

ifstream nameList; 
nameList.open("names.txt"); 
do{ 
     { 
      nameList.getline(line,SIZE); 
      strcpy (list[count].name, line); 
      } 
     count++; 
}while((ch=nameList.peek())!=EOF); 

nameList.close(); 
関連する問題