2014-02-19 27 views
0

我敢肯定,這是一個常見問題,但我找不到類似於我的例子,所以.. 我有一個名爲input.txt的文本文件,它具有: 0.00.0005434 0.0005678 1.0023423 0.00063452 1.0001546 0.00074321 1.00017654其中。 現在我想編寫一個程序將其讀入數組,然後快速檢查它是否工作。到目前爲止,我得到了:輸入數字從txt文件到數組

#include <iostream> 
#include <fstream> 
#include <string> 
using namespace std; 

int main() 
{ 
    double PA[8]; 
    int n; 
    ifstream myfile ("input.txt"); 
    if (myfile.is_open()) 
    { 
     while (! myfile.eof()) 
     { 
      getline (myfile,line); 
      cout << PA[line]<< endl; 

     } 
     myfile.close(); 
    } 
    else cout << "Unable to open file"; 
    for (n=0; n<8; n++) // to print the array, to check my work 
    { 
     cout << " {" << PA[n] << "} "; 
} 

    system("PAUSE"); 
    return 0; 
} 

我到目前爲止的問題是,我不斷收到錯誤:行沒有聲明。我想在稍後使用浮點數來計算新數據。我認爲我做錯了..任何幫助?謝謝!

回答

0

DECLARE線可變

int n, line = 0; 
std::string value; 

適當的負載數據:

getline (myfile,value); 
PA[line] = atof(value.c_str()); 
cout << PA[line]<< endl; 
line++; 
+0

你是什麼意思通過加載數據? – Emil

+0

從輸入文件加載數據到雙精度數組代碼塊之間while(! myfile.eof()){...}) – ziollek

+0

謝謝!這主要工作,除了它似乎只做第一個數字,我無法得到循環工作,似乎我只是乘以錯誤:P – Emil

0

這裏

cout << PA[line]<< endl; 

可變線未聲明。如果你聲明它,你也必須給它一個值,否則它是未定義的,並且PA[line]是未定義的,換句話說:將會崩潰。

整個塊時顯得可疑:

while (! myfile.eof()) 
{ 
    getline (myfile,line); 
    cout << PA[line]<< endl; 

} 

你確定,則對getline電話嗎?

我知道這個簽名函數getline:

ssize_t getline(char **lineptr, size_t *n, FILE *stream); 

而且甚至不匹配您的版本的參數個數。

如果你的輸入文件有超過8行的輸入,比while循環將有許多交互 - 你的數組只有8個元素的空間。

0

你需要聲明你所謂的「線」如下變量:

int i=0; 

    while (! myfile.eof() && i<8) 
    { 
     std::string line; // this was the missing statement 

     getline (myfile,line); 

     double value = atof(line.c_str()); // convert line form char* to double 

     PA[i++] = value; 

     cout << value << endl; 

    } 

請注意,您需要將線轉換爲雙並使用遞增變量「我」(例如,像我一樣做千萬不要通過檢查我agains大小(目前爲8,不應該硬編碼的,順便說一句)溢出PA能力。

還要注意的是,你不應該打印出結果,如果文件訪問失敗。