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;
}
4

2 回答 2

0

您永远不会检查流是否曾经初始化为所需的状态。我将首先检查流是否能够打开给定的参数: if(inputFile.is_open)

于 2013-08-26T21:59:40.370 回答
-1

correctAnswers 是一个 int 数组,您试图将来自文件的字符串复制到它上面。我建议您使用辅助变量来存储从文件中抓取的行,然后根据需要对其进行操作。此外,您可能希望确保不超过文件限制的结尾......

于 2013-08-26T21:58:54.333 回答