2012-03-15 40 views
0

只需要一般的項目幫助。 基本上我需要爲8名球員做到這一點。這些數據來自一個我應該打入的文件。前5場比賽的前5個數字,下一個籃板數據,然後是塊數。我假設我需要調用一個循環來讀取名字,姓氏,積分,籃板和塊,處理該信息,然後輸出信息。任何提示/建議?從文本文件通過文件排序/返回信息

例如:從什麼我應該

Thomas Robinson 17 28 10 16 10 11 12 13 8 9 1 1 1 0 1 

前把這些信息返回

  Game Log 
----------------------------------------------------------------------------- 

Player Name : Thomas Robinson 
----------------------------------------------------------------------------- 
Game #  Points  Rebounds  Blocks 
----------------------------------------------------------------------------- 
    1 17 11 1 
    2 28 12 1 
    3 10 13 1 
    4 16 8 0 
    5 10 9 1 
----------------------------------------------------------------------------- 
+2

歡迎來到Stack Overflow!你試過什麼了?什麼給你帶來了問題? – 2012-03-15 01:30:38

+0

老師不會讓我們調用預定義的函數,所以我們必須創建自己的函數。使用數組和循環。現在我正在努力獲得一個數組,以加載玩家的名字並將統計數據插入表中。 – user1270476 2012-03-15 01:38:19

回答

0

我認爲這是家庭作業,但因爲我不知道是哪個功能可以使用,哪些功能不能,我的答案可能不能滿足要求。

第一次看,我有三個想法。使用ifstream::get()

ifstream in_file; 
in_file.open("your_file_name.txt"); 
char ch; 
string str = ""; 
while(in_file.get() != '\n') 
{ 
    str = ""; 
    while((ch = in_file.get()) != ' ') 
    { 
    // add ch to str. 
    str += string(&ch, 1); 
    } 
    // push str into an array, vector, stack, etc. 
    /*...*/ 
} 
in_file.close(); 

2)讀行成一個string,然後用split功能

1),你可以找到如何到處實現split功能。

3)使用ifstream::getline()函數,它提供了一個delemiter參數。

,你可以找到ifstream::get()使用和ifstream::getline()herehere

我在1提供的代碼)可能不是一個很好的做法,你應該檢查「EOF」流錯誤,in_file.open()的異常等。

順便說一句,我第一次寫的代碼是一個錯誤代碼,您不能使用str += string(ch),您應該寫str += string(&ch, 1)str += string(1, ch)str += ch你可以找到string的構造here。對不起,再次出現錯誤代碼。

+0

'str + = string(ch);'真的嗎?此外,您不會正確處理意外的EOF(或其他流錯誤)。 – Josh 2012-03-15 02:13:06

+0

感謝幫助,即時調查現在執行此權利。我會讓你知道它很快會如何。 – user1270476 2012-03-15 02:17:25

+0

@Josh嗯......代碼沒有正確驗證,只是提供瞭解決問題的方法。 – shengy 2012-03-15 02:28:35

0

如果所有內容都由空格和換行符分隔,則可以使用「>>」運算符很好地解析文件。 「>>」運算符是如何工作的。所以,是的,你需要一個循環。基本上你想循環工作是這樣的:

(我從來不知道你可以在Comp Sci 1中做到這一點。它會救了我很多麻煩......我曾經做過類似其他答案的事情這樣做。)

(我也假設你知道如何打開一個txt文件作爲ifstream的。如果不是看到http://www.cplusplus.com/reference/iostream/ifstream/open/

int temp; 
int n = 0; 
int x = 1; 

while(textfile >> temp) // Each time through the loop, this will make temp 
         // the next value in the file. It will stop when 
         // there's nothing more to read. 
{ 
    /* Now it's going to go from left to right through the file, so you 
     need some logic to put it in the right place. you know that every 
     five numbers start a new column, so:*/ 

    array[x][n] = temp; //Start x at 1 because you're skipping the first column 
    n++; 
    if (n == 5) { 
     n = 0; 
     x++; //Every five values, move on to the next column 
    } 

現在你的陣列將擁有的東西需要的地方是。只需按計劃輸出。