Used .ignore('\n') and the Getline function that follows is only taking half of the input from file

冷暖自知 提交于 2020-06-09 05:24:06

问题


I tried to make sure what I'm asking wasn't a duplicate since this must be a very beginner mistake but I couldn't find something similar but if someone has a reference to a similar post that'd be great as well anyways So I'm trying to make a battleship game that reads in the ship placement from a .csv file but before it places the ships it goes through the file and makes sure all the ships are found in the file.

The data in the file is formatted as follows:

Carrier,B2,H
Battleship,D4,V
Cruiser,G4,H
Submarine,G5,V
Destroyer,G8,H

The part that is causing me issues in my code is this block:

cout << "File successfully located!\n Making sure all ships are in file...\n";
while (shipPlacement.good()) {
        getline(shipPlacement, shipType, ',');
        cout << shipType << endl;
        shipPlacement.ignore('\n');
    }

I want it to only take in the battleship type and ignore everything else in the file. The first line is read in correctly it stops reading until the set delimiter, great! and then I want it to ignore everything that follows until the next line so I put shipPlacement.ignore('\n') and from that point it should loop again reading in the next ship up until the delimiter, etc. am I missing something here? what is happening is only half of the ship type is getting taken as input. This is the output I'm getting:

Making sure all ships are found in file...
Carrier
leship
ser
arine
royer

This is probably a simple fix but I can't see what's in front of me it looks like, Any help or guidance is appreciated!


回答1:


The first argument to ignore is the maximum number of characters to discard, not the delimiter (and since you didn't specify a delimiter, it was always discarding the maximum). Your \n is being interpreted in binary as the number 10, which results in the next 10 characters being skipped (,B2,H⏎Batt). You should instead do shipPlacement.ignore(x, '\n'), where x is the most characters you ever expect to see before the newline.



来源:https://stackoverflow.com/questions/61400134/used-ignore-n-and-the-getline-function-that-follows-is-only-taking-half-of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!