2016-03-08 228 views
-2

我的代碼是用於從文本文件中讀取數據的,我希望此代碼從文本文件逐行讀取數據,目前它只是讀取我的文本文件的第一行,而不會到下一行。 「學生」是文本文件。和文本文件包含下面給定的數據,從文件中讀取多行文件

[ALI,DBA,BITF11M001,3.0,3.57

ASIF,DBA,BITF11M002,3.5,3.9

ALI,OOP,BITF11M001,3.5,3.57

ASIF,OOAD,BITF11M002,3.7,3.9

ALI,OOAD,BITF11M001,3.5,3.57

ASIF,OOP,BITF11M002,4.0,3.9

ALI,DSA,BITF11M001,3.0,3.57

ASIF,DSA,BITF11M002,4.0,3.9 ]

#include <iostream> 
#include <fstream> 
#include <string> 
#include <cstring> 

using namespace std; 

struct student_attribute 

{ 
    string name [20]; 
    string course [20]; 
    string roll_no[20]; 
    float GPA [20]; 
    float CGPA [20]; 

}; 

int main() 

{ 
    int i =0; 

    int count ; 

    student_attribute data; 

    ifstream myfile ("Students.txt"); 


    string line; 

     while (myfile) 

    { 
     getline(myfile, data.name[i], ','); 

     getline(myfile, data.course[i], ','); 

     getline(myfile, data.roll_no[i], ','); 

     myfile >> data.GPA[i]; 

     myfile >> data.CGPA[i]; 

     count++; 
    } 


    myfile.close(); 

    for(int index = 0; index < count; index++) 

    { 
     cout << data.name[index] << " "; 
    } 

    for(int index = 0; index < count; index++) 

    { 
     cout << data.course[index] << " "; 
    } 

    for(int index = 0; index < count; index++) 

    { 
     cout << data.roll_no[index] << " "; 
    } 

     for(int index = 0; index < count; index++) 

    { 
     cout << data.GPA[index] ; 
    } 

    return 0; 
} 
+0

''''總是'0' – Hacketo

+0

你永遠不會改變你的循環中的'i'的值,所以你把所有的東西都讀入同一個數組元素 – Galik

+0

'擁有'student_attribute'數組比通常情況下更有意義'student_attribute',每個成員都是一個數組。 – crashmstr

回答

1
myfile >> data.GPA[i]; 

這將工作,從輸入讀出號碼3.0。下一個未讀字符是','

myfile >> data.CGPA[i]; 

這是行不通的,因爲','不是float。匹配失敗,失敗位被設置爲myfile,while (myfile)false,循環結束。

你的代碼還有其他一些問題,其中一些已經被註釋過了,但這就是爲什麼只有(部分)第一行被實際讀取的原因。