1

Scenario: Read numbers from file and create dynamic 2d array accordingly The first line of data file represents the rooms and rest of the lines represent the number of person in the room

For example:

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;
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
Anonymous
  • 71
  • 7
  • 1
    Unless this is an exercise in using pointers and dynamic allocation, don't do any of that. Use [`std::vector`](http://en.cppreference.com/w/cpp/container/vector) instead. – Some programmer dude Sep 16 '18 at 07:23
  • 1
    Other than that, why use a loop for the first input? And why not use a `for` loop for the other input? – Some programmer dude Sep 16 '18 at 07:25
  • As for your problem, can you please elaborate on it? Are the number you read form the file read correctly? Is `new[]` not throwing exceptions? Have you tried to [debug your program](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)? Does it do what you expect it to? – Some programmer dude Sep 16 '18 at 07:33
  • The first loop used to extract the value of first line from text file and break the loop The second loop used to extract value of second line till last line – Anonymous Sep 16 '18 at 07:42
  • Not throwing any exceptions. This is the output: numRoom:4 i:0 numstation:4 i:1 numstation:6 i:2 numstation:5 i:3 numstation:3 – Anonymous Sep 16 '18 at 07:44
  • The first loop won't even iterate fully even once, as you unconditionally `break` out of the loop *always*. So, why a loop? And you don't need to open the same file twice, just continue to read from it. The logic of your program is... *weird* I would say. – Some programmer dude Sep 16 '18 at 07:52
  • And if your output (which you should copy-paste into the *question*) is correct, then you allocate the correct amount of elements. – Some programmer dude Sep 16 '18 at 07:52
  • I'll improvise my logic again, if the output is correct anyway I can confirm the size? – Anonymous Sep 16 '18 at 07:55
  • Using pointers? No. If you have a pointer to an "array", all you really have is a pointer to its first element. There's no (standard and portable) way to get the size of the allocated data. If you use `std::vector` it's *really* easy. – Some programmer dude Sep 16 '18 at 07:56
  • Can I try to access out of bound of array to confirm the size? even if it is not the legit way to do so – Anonymous Sep 16 '18 at 08:00
  • No, you can't, since for pointer you don't even *know* where the end of the"array" is. Again, with a pointer you only have a pointer to the first element, and that's it. Added answer with "better" code. – Some programmer dude Sep 16 '18 at 08:05

1 Answers1

1

A better way to do your current program, using std::vector, could be like this:

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

As you can see, it's now possible to get the "sizes" of the data after you're done with the reading from the file.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • This method is easier but I think my lecturer wants me to use pointer method lol, just realised But somehow the size of room increased from 4 to 8 which supposed to be only 4 – Anonymous Sep 16 '18 at 12:36
  • I am still thinking how to do with pointers – Anonymous Sep 16 '18 at 12:37