2013-08-26 79 views
0

任何人都可以告訴我爲什麼我的數組沒有填滿我想從我的數據文件中獲取的信息嗎?當我輸出數組時,它只是給我垃圾。提前致謝。爲什麼這個文件沒有讀入我的數組?

#include <iostream> 
#include <fstream> 

using namespace std; 

// function main begins program execution 
int main() 
{ 
    /* input correct answers file */  
    const int ARRAY_SIZE = 20;  // Array size 
    int correctAnswers[ARRAY_SIZE]; // Array to hold correct answers 
    int count = 0;     // Loop counter variable 
    ifstream inputFile;    // Input file stream object 

    // open the file 
    inputFile.open("c:\\correctanswers.txt"); 

    // read the numbers from the file into the array 
    while (count < ARRAY_SIZE) 
    { 
     inputFile >> correctAnswers[count]; 
     count++; 
    } 

    // close the file 
    inputFile.close(); 

    // display the correct answers 
    cout << "The correct answers are: "; 
    for (int index = 0; index < count; index++) 
     cout << correctAnswers[index] << " "; 
    cout << endl; 
    system ("pause"); 

    return 0; 
} 
+0

您是否在Windows/Linux中嘗試?什麼是錯誤信息? –

+0

該文件的內容是什麼?文件correctanswers.txt是否存在? –

+1

您不會在輸入流上檢查錯誤。我的猜測是該文件無法打開,或者它不包含整數。 – paddy

回答

-1

correctAnswers是一個int數組,你試圖將其拷貝到它的字符串來自該文件。我建議你使用一個輔助變量來存儲從文件中抓取的行,然後根據需要操作它。此外,您可能希望確保不超過文件限制的末尾...

0

您從不檢查流是否已初始化爲所需狀態。我會開始檢查流是否能打開給定的參數:if(inputFile.is_open)

相關問題