简体   繁体   中英

Using getline to read from a file into a string and then pushing that string back on a vector

Okay so I'm still fairly new to coding in general so I might just be missing something that is obvious to everyone else. That being said though I'm trying to just print a simple map from a text file but I want to load the info into a vector first. Problem is I only seem to be loading the last line. I am using curses for the printing and all that.

Here is the LevelControl code right now all I have is the load function and the :

void LevelControl::loadLevel(string levelName)
{
    ifstream level;
    string transferLine;
    level.open(levelName);
    if(level.fail()){perror("Level");}
    while(getline(level, transferLine));
    {
        int counter = 0;
        loadedLevel.push_back(transferLine);
        printw("\n");
        counter++;
        transferLine.clear();
    }
}

void LevelControl::printLevel()
{
    int mapSizeX = loadedLevel.size();
    string loadedString;
    for(int i = 0; i < mapSizeX; i++ )
    {
        loadedString = loadedLevel[i];
        mapSizeY = loadedString.size();
        printw("%s \n", loadedString.c_str());
        refresh();
        loadedString.clear();
    }
}

This is my main()

int main()
{
    LevelControl currentLevel;
    initscr();
    currentLevel.loadLevel("level.txt");
    bool loopGame = true;
    while(loopGame)
    {
        currentLevel.printLevel();
        getch();
    }
    endwin();
    return 0;
}

This is the map I'm trying to print and is exactly how it's written in the txt file:

#########*
#........#
#........#
#........#
#........#
#........#
#........#
#........#
#........#
##########

Instead all I get is:

##########

So yeah...no idea why it's only reading the last line. I have seen many examples of getline used in a while loop to print an entire file. I just don't know why I can't push_back it all to a vector. My print function checks the size of the vector and I always get 1. So I'm pretty sure my print function is working (or at least not causing this issue haha)

Anyways any help is much appreciated!!

while(getline(level, transferLine).good());

This loop has an empty controlled statement. So the loop reads the lines but doesn't do anything with them, until on loop termination when only the last read line will be put to the vector.

while(getline(level, transferLine))//; remove this semi-colon
{
        int counter = 0;//might want to consider the purpose of this also
        loadedLevel.push_back(transferLine);
        printw("\n");
        counter++;
        transferLine.clear();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM