2012-02-13 63 views
0

在C++中的新手,我試圖創建一個統計程序來練習編碼。我希望得到一個文本文件,讀取它並將值存儲到數組中,我可以執行數學運算。我正在上面這裏將標記存儲到數組中

main() 
{ 
     char output[100]; 
     char *charptr; 
     int age[100]; 
     ifstream inFile; 
     inFile.open("data.txt"); 
     if(!inFile) 
     { 
      cout<<"didn't work"; 
      cin.get(); 
      exit (1); 
     } 

     inFile.getline(output,100); 
     charptr = strtok(output," "); 
     for (int x=0;x<105;x++) 
     { 
      age[x] = atoi(charptr); 
      cout<<*age<<endl; 

     } 

    cin.get(); 
} 

停留在代碼中,我試圖受青睞存入int數組「年齡」,保持在年齡該文件的第一行。我打算如前所述使用strtok,但我無法將令牌轉換爲數組。

正如您明顯看到的,我是一個完整的noob,請耐心等待,因爲我正在自己學習。 :)

感謝

P.S:我看過類似的線程,但我無法跟隨給出有詳細的代碼。

+4

我建議你考慮使用的std ::矢量這樣做 – shuttle87 2012-02-13 15:22:38

+0

同樣的問題恰好沒有討論最近:http://stackoverflow.com/questions/9241449/read-files-by-character-c/9241472 – Lol4t0 2012-02-13 15:23:39

+0

「輸出」是程序輸入的一個奇怪的名字。即使你開始學習,適當的命名也是一個很好的習慣。 – molbdnilo 2012-02-13 16:44:03

回答

5

沒有與for環的幾個問題:

  • for環走出去界外,由於age爲100元,但中止條件的可能性是x < 105
  • charptr沒有檢查是用
  • NULL之前內部for環路strtok()沒有後續調用
  • 印刷age個元件是不正確

以下將是for環的例子修復:

charptr = strtok(output, " "); 
int x = 0; 
while (charptr && x < sizeof(age)/sizeof(age[0])) 
{ 
    age[x] = atoi(charptr); 
    cout << age[x] << endl; 
    charptr = strtok(NULL, " "); 
    x++; 
} 

由於這是C++,建議:

  • 使用std::vector<int>代替固定的大小陣列
  • 使用std::getline()來避免指定一個固定大小的緩衝區來讀取行
  • 使用std::copy()istream_iterator解析整數

例如線:

#include <iostream> 
#include <fstream> 
#include <sstream> 
#include <string> 
#include <vector> 
#include <algorithm> 
#include <iterator> 

int main() 
{ 
    std::vector<int> ages; 
    std::ifstream inFile; 
    inFile.open("data.txt"); 
    if(!inFile) 
    { 
     std::cout<<"didn't work"; 
     std::cin.get(); 
     exit (1); 
    } 

    std::string line; 
    std::getline(inFile, line); 

    std::istringstream in(line); 

    std::copy(std::istream_iterator<int>(in), 
       std::istream_iterator<int>(), 
       std::back_inserter(ages)); 

    return 0; 
} 
+0

謝謝hmjd。我現在正在'練習矢量',因爲我的課程筆記沒有涵蓋他們。將盡快嘗試您的解決方案。非常感謝。順便說一句,我正在閱讀dietel&dietel(太冗長)。 – 2012-02-13 15:53:52