【问题标题】:2D Dynamic Array Based on User Input [duplicate]基于用户输入的二维动态阵列
【发布时间】:2019-02-20 10:36:36
【问题描述】:

场景: 从文件中读取数字并相应地创建动态二维数组 数据文件第一行代表房间,其余行代表房间人数

例如:

4 4 6 5 3

一共4个房间,第一个房间有4个人,第2个房间有6个人...

到目前为止,这是我的代码,如何检查我是否创建了大小正确的动态数组?

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

using namespace std;

int main()
{
    ifstream readFirstLine("data.txt");
    ifstream readData("data.txt");

    string line;

    int numRoom, numPerson = 0;

    int i = -1;

    while (getline(readFirstLine, line))
    {
        istringstream linestream(line);

        if (i == -1)
        {
            linestream >> numRoom;
            cout << "numRoom:" << numRoom << endl;

            break;
        }

    }

    readFirstLine.close();

    int** numRoomPtr = new int*[numRoom];

    while (getline(readData, line))
    {
        istringstream linestream(line);

        if (i == -1)
        {

        }
        else
        {
            linestream >> numPerson;
            numRoomPtr[i] = new int[numPerson];

            cout << "i:" << i << endl;
            cout << "numPerson:" << numPerson<< endl;
        }


        i++;
    }

    readData.close();




    return 0;
}

【问题讨论】:

  • 除非这是一个使用指针和动态分配的练习,否则不要这样做。请改用std::vector
  • 除此之外,为什么要对第一个输入使用循环?为什么不对其他输入使用for 循环?
  • 至于你的问题,能否详细说明一下?您从文件中读取的数字是否正确读取? new[] 不抛出异常吗?你试过debug your program吗?它是否符合您的预期?
  • 第一个循环用于从文本文件中提取第一行的值并打破循环第二个循环用于提取第二行的值直到最后一行
  • 不抛出任何异常。这是输出: numRoom:4 i:0 numstation:4 i:1 numstation:6 i:2 numstation:5 i:3 numstation:3

标签: c++ arrays visual-c++ multidimensional-array dynamic


【解决方案1】:

使用std::vector 执行当前程序的更好方法可能是这样的:

#include <iostream>
#include <vector>
#include <fstream>

int main()
{
    std::ifstream dataFile("data.txt");

    // Get the number of "rooms"
    unsigned roomCount;
    if (!(dataFile >> roomCount))
    {
        // TODO: Handle error
    }

    // Create the vector to contain the rooms
    std::vector<std::vector<int>> rooms(roomCount);

    for (unsigned currentRoom = 0; currentRoom < roomCount; ++currentRoom)
    {
        unsigned personCount;
        if (dataFile >> personCount)
        {
            rooms[currentRoom].resize(personCount);
        }
        else
        {
            // TODO: Handle error
        }
    }

    // Don't need the file anymore
    dataFile.close();

    // Print the data
    std::cout << "Number of rooms: " << rooms.size() << '\n';
    for (unsigned currentRoom = 0; currentRoom < rooms.size(); ++currentRoom)
    {
        std::cout << "Room #" << currentRoom + 1 << ": " << rooms[currentRoom].size() << " persons\n";
    }
}

如您所见,现在可以在完成文件读取后获取数据的“大小”。

【讨论】:

  • 这个方法比较简单,但是我觉得我的讲师想让我使用指针方法大声笑,刚刚意识到 但是不知何故房间的大小从 4 增加到 8 应该只有 4
  • 我还在想如何处理指针
猜你喜欢
  • 2016-04-22
  • 2022-11-25
  • 2016-12-20
  • 2023-03-06
  • 2019-06-18
  • 1970-01-01
  • 1970-01-01
  • 2017-10-06
  • 2016-08-02
相关资源
最近更新 更多