c++ - 基于用户输入的二维动态数组

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

<分区>

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

例如:

4
4
6
5
3

total 4 rooms, 1st room has 4 people, 2nd room has 6 people...

So far this is my code, how do I check I've created the dynamic array with correct size?

#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 ,可能是这样的:

#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";
    }
}

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

关于c++ - 基于用户输入的二维动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52351880/

相关文章:

java - 打印范围,如果缺少数字

c# - 如何在 Visual C#/C++ 中实现文本转语音 (TTS)?

c++ - 如何将列表控件项标记为选中?

c++ - 使用 c++/vC++ 将结构数组和二维数组传递给函数

c++ - 模板参数推导错误

javascript - 未找到 UI/模板模块 NativeScript

c++ - 使用 boost::random 库获取整数随机值而不是实际值

c++ - 为什么我们可以删除数组,但不知道 C/C++ 中的长度?

c++ - C++ 程序执行错误 : static executable calls DLL library

c++ - RayTracer 球面贴图