将文件中的数据读入数组 \- C

新手上路,请多包涵

我想从我的输入文件中读取数据

70 95 62 88 90 85 75 79 50 80 82 88 81 93 75 78 62 55 89 94 73 82

并将每个值存储在一个数组中。这个特殊问题还有更多(其他功能现在被注释掉了),但这才是真正给我带来麻烦的地方。我在上一个关于数据和数组的问题上看了几个小时,但我找不到我在哪里犯了错误。

这是我的代码:

 #include <iostream>
#include <fstream>
#include <string>

using namespace std;

const int SIZE = 22;
int grades[SIZE];

void readData() {

    int i = 0;
    int grades[i];

    string inFileName = "grades.txt";
    ifstream inFile;
    inFile.open(inFileName.c_str());

    if (inFile.is_open())
    {
        for (i = 0; i < SIZE; i++)
        {
            inFile >> grades[i];
            cout << grades[i] << " ";
        }

        inFile.close(); // CLose input file
    }
    else { //Error message
        cerr << "Can't find input file " << inFileName << endl;
    }
}
/*
    double getAverage() {

        return 0;
    }

    void printGradesTable() {

    }

    void printGradesInRow() {

    }

    void min () {
        int pos = 0;
        int minimum = grades[pos];

        cout << "Minimum " << minimum << " at position " << pos << endl;
    }

    void max () {
        int pos = 0;
        int maximum = grades[pos];

        cout << "Maximum " << maximum << " at position " << pos << endl;
    }

    void sort() {

    }
*/

int main ()
{
    readData();
    return 0;
}

这是我的输出:

  0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

感谢您的时间。

原文由 dev_P 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 579
2 个回答

问题是您要声明一个大小为 1 的本地 grades 数组,隐藏全局 grades 数组。不仅如此,您现在正在访问超出范围的数组,因为本地 grades 数组只能容纳 1 个项目。

所以摆脱这条线:

 int grades[i];

但是,需要指出的是:

 int i = 0;
int grades[i];

不是有效的 C++ 语法。您只是错误地偶然发现了这一点,但如果使用严格的 ANSI C++ 编译器编译该代码将无法编译。

C++ 中的数组必须使用常量表达式声明,以表示数组中的条目数,而不是变量。您无意中使用了一个非标准的编译器扩展,称为 可变长度数组 或简称 VLA。

如果这是为了学校作业,请不要以这种方式声明数组(即使您打算这样做),因为它不是正式的 C++。如果你想声明一个动态数组,这就是 std::vector 的用途。

原文由 PaulMcKenzie 发布,翻译遵循 CC BY-SA 3.0 许可协议

我在阅读文件时没有看到任何问题,您只是混淆了成绩的全局变量和局部变量

你不需要这个

int i = 0;
int grades[];

函数内部 readData

 #include <string>

using namespace std;

const int SIZE = 22;
int grades[SIZE];

void readData() {

    string inFileName = "grades.txt";
    ifstream inFile;
    inFile.open(inFileName.c_str());

    if (inFile.is_open())
    {
        for (int i = 0; i < SIZE; i++)
        {
            inFile >> grades[i];
            cout << grades[i] << " ";
        }

        inFile.close(); // CLose input file
    }
    else { //Error message
        cerr << "Can't find input file " << inFileName << endl;
    }
}

int main()
{
    readData();
    return 0;
}

输出

原文由 Hariom Singh 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题