2012-02-12 38 views
-1

我無法將指針回零,因此我可以在回聲後再次通過數據。無法使指針回零

#include <iostream> 
#include <fstream> 
#include <string> 
#include <iomanip> 

using namespace std; 

int main() 

{ 
    ifstream infile; 

    infile.open ("scores.txt" , ifstream::in); 

    int ch = infile.get(); 
    string lastname; 
    char gender= ' '; 
    string collegetype; 
    float score=0; 
    float scoreMALE=0; 
    float scoreFEMALE=0; 
    int countMALE=0; 
    int countFEMALE=0; 

    while (!infile.eof()) 
    { 

      cout << (char) ch; 
      ch = infile.get(); 
    } 

    infile.seekg(0,ios::beg); 
    while (!infile.eof()) 
    { 
    infile>>lastname>>gender>>collegetype>>score; 
    if(gender == 'm') 
      { 
       scoreMALE = scoreMALE + score; 
        countMALE++; 
      }   

    else if (gender == 'f') 
      { 
        scoreFEMALE = score; 
        countFEMALE++; 
      } 
    } 

    cout<<"\n\n\n The total Female Scores is"<<countFEMALE<<"\n\n\n The total of the male scores is"<<countMALE; // Checking to see if file works 


    infile.close(); 

    cout<<"Press <Enter> to Exit"; 
    cin.ignore(); 
    cin.get();  
    return 0;     
} 

這裏的輸入文件:

貝利中號CC 68 哈里森˚FCC 71 格蘭特中號聯合國75 彼得森˚F聯合國69 許中號聯合國79 鮑爾斯中號CC 75 安德森˚F聯合國64 阮˚FCC 68 夏普˚FCC 75 瓊斯中號UN 75 麥克米蘭˚FUN 80 加布裏埃爾˚FUN 62

+0

你的代碼沒有任何指針。 – 2012-02-12 18:43:14

+0

對不起,但你的問題不清楚。你是否問過在讀完文件之後將文件指針移回到文件的開頭?如果是這樣,你已經有了這個代碼(你只需要做一次)。 – 2012-02-12 18:43:41

+1

在第二輪之前添加'infile.clear();'。 – 2012-02-12 18:43:53

回答

0

將infile.clear()添加到infile.seekg(0,ios :: beg)之上,導致代碼在此循環遍歷第二個循環(如建議的Kerreck-SB)。

這樣做後,你的分數仍然爲0的原因是由於字符比較使用的是不正確的情況。例如。 'f'和'm'代替輸入文件中的'F'和'M'。

+0

我剛剛意識到不到一分鐘前人物是小寫字母。感謝您的幫助,學習C++可能會讓人感到痛苦! – kd7vdb 2012-02-12 19:12:12