繁体   English   中英

从具有多列整数的文件中读取并将其放入数组

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

我正在创建一个具有保存和继续功能的命令行扫雷游戏。 我的代码生成了一个名为“ save.txt”的文件,该文件存储了地雷的位置以及玩家已打开的单元格。 它分为两列,两列之间用一个空格隔开,其中左列代表单元格的行,右列代表由我的代码生成的矩阵中单元格的列。 以下是示例运行后save.txt的内容:

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

您可能已经注意到Mine endCell open end 这两个基本上将数字分为两组,第一个是用于放置地雷的位置,第二个是用于玩家打开的游戏室的位置。 我创建了一个代码,该代码为文本文件包含整数的每一列生成一个数组:

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

如您所见,这不适用于我的文本文件,因为它包含非整数文本。 基本上,我想按照openedCol描述创建四个数组: mineRowmineColopenedRowopenedCol

除了自己解析字符串并执行字符串操作外,您还可以重新定义文件格式以包含标头。 然后,您可以解析一次并将所有内容保留为数字。 即:

让标题为前两行

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

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

然后,您只需知道mineRow的40,mineCol的30,openedRow的20,openedCol的10,因为您知道它们的长度。 这可能会更难调试,但是可以让您更好地隐藏保存状态,以免对其进行轻易的修改。

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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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