程序输出应该是:读取数据到一个数组
的数字是: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' –