程序輸出應該是:讀取數據到一個數組
的數字是:101 102 103 104 105 106 107 108 108 110
但我的輸出是:
的數字是:0 0 0 0 0 0 0 0 32767 1606416272
這是我的代碼:
// This program reads data from a file into an array.
#include <iostream>
#include <fstream> // To use ifstream
using namespace std;
int main()
{
const int ARRAY_SIZE = 10; // Array size
int numbers[ARRAY_SIZE]; // Array number with 10 elements
int count = 0; // Loop counter variable
ifstream inputFile; // Input file stream object
// Open the file.
inputFile.open("TenNumbers.rtf");
// Read the numbers from the file into the array.
while (count < ARRAY_SIZE && inputFile >> numbers[count]){
count++;
}
// Close the file.
inputFile.close();
// Display the numbers read:
cout << "The numbers are: ";
for (count = 0; count < ARRAY_SIZE; count++){
cout << numbers[count] << " ";
}
cout << endl;
return 0;
}
這是TenNumbers.rtf文件,我從讀取數據的內容:
101
102
103
104
105
106
107
108
109
110
更新1: 我用txt文件,但結果嘗試是相似的。
的數字是:0 0 0 0 0 0 0 0 1573448712 32767
更新2: 我發現那裏的問題了。在運行if (inputFile.good())
後,我發現文件沒有打開。
檢查inputFile'的'狀態count]'操作,以確保從文件加載時沒有錯誤。還要考慮如果文件包含少於「ARRAY_SIZE」的數字會發生什麼。我還建議使用'std :: array'或'std :: vector',它們在良好的調試器中執行更多的檢查。 –
我真的不知道.rtf格式。你確定它以ASCII兼容格式存儲文本?如果不是,那可能是問題所在。快速瀏覽一下wiki頁面可以發現,它至少可能包含額外的格式化字符。嘗試使用正常的.txt文件。 –
我試過使用txt文件,但結果是相似的。 '數字是:0 0 0 0 0 0 0 0 1573448712 32767' –