HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

2D Vector: Loading values from .txt file

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
fileloadingvaluesfromtxtvector

Problem

I've written a program that runs through a matrix of numbers, ranging from 0 to 2, and stores the results in a 2D vector.

I'm using the values in the 2D vector as the profile for a tile map for a game engine.

I want this to be optimal, and as this is my first attempt at it, I doubt that it is but it does work as is.

Any suggestions for improvement or obvious errors I've made?

The entire project can be found here:
link

Thanks in advance.

// NOTE (Devan): Opening the file.
    std::ifstream mapFile ( fileToOpen );
    if ( !mapFile.is_open () )
    {
        printf ( "Error: Could not open file: %s\n", fileToOpen );
        return;
    }

    // NOTE (Devan): Setting the dimensions of the map. The width and height are taken from the first two entries of the text file.
    unsigned int width = 0;
    unsigned int height = 0; 
    mapFile >> width;
    mapFile >> height;

    int current = 0;
    for ( unsigned int y = 0; y  innerVec;

        for ( unsigned int x = 0; x > current;

            // NOTE (Devan): Checking if the input is within the tile type boundaries. Current Types: ( 0 : 2 )
            if( current >= 0 && current <= 2 )
            {
                innerVec.push_back ( current );
            }
            // NOTE (Devan): If the input is outside of the boundaries simply push 0 into the inner vector.
            else
            {
                innerVec.push_back (0);
            }
        }
        tileMap.push_back ( innerVec );
    }

    mapFile.close ();

Solution

Your code has a bug. When the very last value cannot be read, it won't detect it. Example:

2 2
1 2
3 invalid


Instead of checking for eof, check whether mapFile >> current returns true.

Code Snippets

2 2
1 2
3 invalid

Context

StackExchange Code Review Q#145038, answer score: 2

Revisions (0)

No revisions yet.