简体   繁体   中英

Reading from a file with multiple columns of integers and putting them into arrays

I am creating a command-line minesweeper game which has a save and continue capability. My code generates a file called "save.txt" which stores the position of the mines and the cells that the player has opened. It is separated into two columns delimited by a space where the left column represents the row of the cell and the right column represents the column of the cell in the matrix generated by my code. The following is the contents of save.txt after a sample run:

3 7
3 9
5 7
6 7
8 4
Mine end
2 9
1 10
3 5
1 1
Cell open end

You may have noticed Mine end and Cell open end . These two basically separate the numbers into two groups where the first one is for the position of the mines and the latter is for the position of the cells opened by the player. I have created a code which generates an array for each column provided that the text file contains integers:

int arrayRow[9];
int arrayCol[9];
ifstream infile("save.txt");
int a, b;
while(infile >> a >> b){
    for(int i = 0; i < 9; i++){
        arrayRow[i] = a;
        arrayCol[i] = b;
    }
}

As you can see, this won't quite work with my text file since it contains non-integer text. Basically, I want to create four arrays: mineRow , mineCol , openedRow , and openedCol as per described by the first paragraph.

Aside from parsing the string yourself and doing string operations, you can probably redefine the file format to have a header. Then you can parse the once and keep everything in numbers. Namely:

Let the Header be the first two rows

Row 1 = mineRowLen mineColLen  
Row 2 = openedRowLen openedColLen  
Row 3...N = data

save.txt: 
40 30  
20 10  
// rest of the entries

Then you just read 40 for the mineRow, 30 for mineCol, 20 for openedRow, 10 for openedCol since you know their lengths. This will be potentially harder to debug, but would allow you to hide the save state better to disallow easy modification of it.

You can read the file line by line.
If the line matches "Mine end" or "Cell open end", continue;
Else, split the line by space (" "), and fill the array.

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