【问题标题】:How to read integers from file into dynamic array如何将文件中的整数读入动态数组
【发布时间】:2015-03-02 05:07:22
【问题描述】:

我正在尝试从文本文件中读取整数并将它们放入一个动态数组中,该数组将表示为分配的向量和矩阵。

输入文件中的几行示例:

3#456
33#123456789

井号前的数字代表向量或矩阵的元素,所以 3# 表示三元素向量,33# 表示 3 行 3 列的矩阵。

阅读这些并不是真正的问题,因为我们被告知我们可以假设我们知道哪些行是矩阵,哪些是向量,但是,我从未使用过 C++ 文件 I/O,所以我不知道如何迭代通过数字 4、5、6 并将它们放入 3、9、12 等元素动态创建的数组中。这是我正在使用的一些示例。

int *a;
int size_a;
char x;

ifstream infile("input.txt");

if (infile.is_open())
{
    infile >> size_a;

    // The x is basically a junk variable used to go past the '#'
    // when reading the file
    infile >> x;

    a = new int[size_a];
}

在那之后,我不知道如何循环到行尾并将剩余的元素放入数组中。例如在这一行中,需要将数字 4、5 和 6 放入 a 数组中,然后停止添加元素并转到下一行处理下一个数组,我不知道该怎么做做任何一个。有什么想法吗?

【问题讨论】:

  • ...您没有使用动态数组。你想要std::vector
  • 不需要向量; new 使操作能够创建大小在运行时而不是在编译时已知的数组。你是对的,这些不是动态调整大小的数组,但它们确实符合 OP 的要求,其中不包括调整大小——只是不知道先验的大小。
  • 您需要将每个数字流式传输到char 变量中(例如“c”),然后您可以使用表达式c - '0' 将其从ASCII 转换为数字。使用这些数字获取正确的 size_a 等值,以及要写入数组/矩阵的元素值。

标签: c++ file-io


【解决方案1】:

以下代码将为您执行此操作。请注意,您不需要在此处使用 new - 您应该只使用 std::vector。在这种情况下,不需要“#”之前的数字,因为您不需要在创建数组时指定数组的大小。

出于这个原因,我还是在这里使用了new 来向您展示如何读取文件的两个部分。

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

int main()
{
    std::ifstream file("input.txt");

    if(file.good()) {
        std::string line;
        std::getline(file, line);
        std::string::size_type pos = line.find('#');
        std::string strSize = line.substr(0, pos);
        std::string strValues = line.substr(pos + 1);
        int size = 0;

        for(char c : strSize) {
            if(size == 0)
                size = static_cast<int>(c - '0');
            else
                size *= static_cast<int>(c - '0');
        }

        int* values = new int[size];

        for(int i = 0; i < size; ++i) {
            values[i] = static_cast<int>(strValues[i] - '0');
        }

        std::cout << "Array of size " << size << " has the following values:" << std::endl;

        for(int i = 0; i < size; ++i) {
            std::cout << values[i] << std::endl;
        }

        delete[] values;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 2014-04-08
    • 2015-11-23
    • 2013-10-06
    • 1970-01-01
    • 2010-09-23
    相关资源
    最近更新 更多