2015-02-07 56 views
1

我有一個包含名稱(char名稱[25]),age(int age)和gpa(float gpa)的struct(RECORD)。我想從這個文本文件中讀取數據:只能從文本文件中讀取一個名稱

Jacqueline Kennedy  33 3.5 
 
Claudia Johnson   25 2.5 
 
Pat Nixon    33 2.7 
 
Rosalyn Carter   26 2.6 
 
Nancy Reagan    19 3.5 
 
Barbara Bush    33 3.4 
 
Hillary Clinton   25 2.5

文件中的每名是25個字符長(即數字是25個字符的權利)。我試圖將這些數據複製到RECORD a [7]的數組中。這是我的代碼:

fstream f; 
 
f.open("data.txt", ios::in); 
 
for (int i = 0; i < 7; i++) 
 
{ 
 
\t f.get(a[i].name, 25); //reads the first 25 characters 
 
\t f >> a[i].age >> a[i].gpa; 
 
} 
 
f.close();

只讀取數據的第一線,但沒有了。我如何讓它繼續其餘的線?

回答

1

我認爲這會有所幫助。首先,您需要讀取數組中的整個文件,並將其轉換爲字符串數組,該數組的長度爲25個字符。然後你只需遍歷該數組來顯示它。

if(f.is_open()) 
{ 
//file opened successfully so we are here 
cout << "File Opened successfully!!!. Reading data from file into array" << endl; 
//this loop run until end of file (eof) does not occ 
    while(!f.eof() && position < array_size) 
    { 
     f.get(array[position]); //reading one character from file to array 
     position++; 
    } 
    array[position-1] = '\0'; //placing character array terminating character 

cout << "Displaying Array..." << endl << endl; 
//this loop display all the charaters in array till \0 
    for(int i = 0; array[i] != '\0'; i++) 
    { 
     cout << array[i]; 
     /*then you can divide the array in your desired length strings, which  here is: Jacqueline Kennedy  33 3.5 
     Claudia Johnson   25 2.5 
     Pat Nixon    33 2.7 
     Rosalyn Carter   26 2.6 
     Nancy Reagan    19 3.5 
     Barbara Bush    33 3.4 
     Hillary Clinton   25 2.5*/ 

    } 
} 
else //file could not be opened 
{ 
    cout << "File could not be opened." << endl; 
} 
相關問題