【发布时间】:2013-08-26 21:41:16
【问题描述】:
谁能告诉我为什么我的数组没有填满我试图从我的数据文件中获取的信息?当我输出数组时,它只会给我垃圾。提前致谢。
#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;
}
【问题讨论】:
-
您在 Windows/Linux 中尝试吗?错误信息是什么?
-
文件的内容是什么?文件正确答案.txt 是否存在?
-
您不对输入流进行错误检查。我的猜测是该文件无法打开,或者它不包含整数。
-
在 Windows 中尝试。它没有给我错误消息;它编译并运行,但在执行 cout 命令时,它会将数组中的数字显示为一堆随机数。
-
天哪!呸!该文件不包含整数。谢谢你。 ::尴尬::