2014-10-12 187 views
-3

爲什麼行數始終爲0?它應該是10,但輸出總是0.該方法有什麼問題嗎?行數始終爲0

int main() { 
    vector<double> doubleCoefficient; // vector to store unknown number of equations (double) 

    /* Read from file and assign values to vector */ 

    //File stream object 
    ifstream inputFile; 
    //Open the txt file 
    inputFile.open("test.txt"); 

    //search for the text file 
    if(!inputFile.is_open()) 
    { 
     cerr << "Error opening file \n"; 
     exit(EXIT_FAILURE); 
    } 
    else 
    { 
     cout << "File found and successfully opened. \n"; 
    } 
    double x; 

    while(!inputFile.eof()){ 

     inputFile >> x; 
     doubleCoefficient.push_back(x); 
    } 

    int count =0; 
    string line; 
    while (getline(inputFile, line)){ 
     count++; 
    } 
    cout << "Number of lines in text file:" << count << endl; 

    inputFile.close(); 
} 

回答

1

隨着while(!inputFile.eof())你去到文件的末尾,所以在那之後,你不能讀取行。 你需要去重新使用fseek()

開始嘗試

fseek (inputFile , 0 , SEEK_SET); 

行計數前。

+0

這是因爲你從file_結尾開始計數_,所以你不會計算任何東西。 – gkovacs90 2014-10-12 14:32:56

+0

@ user3504305請檢查更新 – gkovacs90 2014-10-12 14:50:07