【问题标题】:C++ read integers from file and save into arrayC ++从文件中读取整数并保存到数组中
【发布时间】:2016-03-09 19:35:23
【问题描述】:

我正在制作一个只从文本文件中读取整数的程序。我想创建一个读取整数并将它们存储在数组中的函数,以便以后可以使用该数组通过冒泡排序对它们进行排序。这是我到目前为止所拥有的,但我得到的输出是一些随机的 -803234.... 数字:

void read(int A[max], int& numbers) { 
    ifstream file("ints.txt");
    if (file.is_open()) {
        file >> numbers;

        for (int i = 0; i < numbers; i++) {
            cout << "numbers: " << A[i] << endl;
        }
        file.close();
    }
    cout << "numbers in array: " << A[numbers] << endl;
}

【问题讨论】:

  • 您应该阅读 for 循环中的数字。
  • 代码中的A在哪里填充了数字?
  • 您应该在这里使用标准库容器而不是固定大小的数组。 max 是什么?如何确定它足够大?
  • 您能否粘贴您的输出,以便我们更好地了解发生了什么?
  • 如果您在这方面获得帮助,请公开您在“ints.txt”中的内容。正如@EdHeal 所说,A 从未被触及。

标签: c++ arrays integer


【解决方案1】:
std::vector<int> read_ints(std::istream& is)
{
    std::vector<int> result;
    std::copy(std::istream_iterator<int>(is),
              std::istream_iterator<int>(),
              std::back_inserter(result));
    return result;
}

如果您不能使用向量,那么您就有问题了,因为您现在需要检查文件结尾和数组中的空间不足...

此函数将检查两者,并返回已放入缓冲区的整数数:

template<size_t N>
size_t read_ints(int (&dest)[N], std::istream& is)
{
    size_t i = 0;
    while (i < N && is >> dest[i]) {
        ++i;
    }
    return i;
}

非模板版本:

#define BUFFER_LEN 100

size_t read_ints(int (&dest)[BUFFER_LEN], std::istream& is)
{
    size_t i = 0;
    while (i < BUFFER_LEN && is >> dest[i]) {
        ++i;
    }
    return i;
}

【讨论】:

  • 发帖者是新手,稍微解释一下就不会错了。
  • 我不应该使用向量,抱歉我应该在描述中这么说
  • @vidooo 已更新响应。如果您不能使用模板,请将 N 替换为多个选项。
【解决方案2】:

您不会在任何时候将数字存储在数组中:

void read(int A[max], int& numbers) { 
    ifstream file("ints.txt");
    if (file.is_open()) {
        file >> numbers;

        for (int i = 0; i < numbers; i++) {
            // you're printing A[i] but you haven't stored
            // anything there.
            cout << "numbers: " << A[i] << endl;

我假设 numbers 是文件中的条目数,并且您打算以与读取 numbers 相同的方式读取值,但读取到 A[i]。

cin >> A[i];

您的代码的最后一部分也尝试打印超出数组的最后一个条目:

cout << "numbers in array: " << A[numbers] << endl;

记住,C++ 数组是从 0 开始的,所以 A[numbers] 是 *numbers + 1*th 条目。

【讨论】:

  • 在 for 循环中什么时候将整数存储在数组中?
  • 因为这看起来像是一个教育任务,我不会给你完整的工作示例,但很明显你需要在尝试打印它们之前阅读->存储它们。看看我在哪里发表评论。