任何人都可以向我解释如何根据以下场景制作 C 程序以从文件中读取输入:
12
2-4,7,9;
1,4,11-12;
1,4,10,12;
1,4-8,10-12;
1,8;
1,3-6,8,10-12;
1,3,5-6,8,11;
1,8,10-12;
1-8;
;
2;
2-4,7-10,12;
第一个数字(在第一行)描述了网格的大小,在本例中为 12x12 网格。下面几行描述了网格的每一行占用了多少个单元格。例如,在第一行中,从 2 到 4 和 7 和 9 的单元格被占用;在第二行中,单元格 1、4 和 11 到 12 被占用,依此类推。
现在我有这段代码,但它没有解决我的问题......
#include <stdio.h>
#include <stdlib.h>
void main()
{
char content[3000];
int value;
FILE *ptr_file = fopen("data.txt", "r");
if(!ptr_file)
return 1;
int j;
while(fgets(content, 3000, ptr_file)!=NULL){
printf("%s", content);
value = atoi(content);
for(j=0; j<3000; j++){
value = content[j];
printf("%i", value);
}
}
return 0;
}
控制台抛出一堆随机数......
最佳答案
伪代码:
Open your file
Read the first line
Extract the value N
Allocate your grid
Loop N times
Read a line
If not an empty line, ie. semi-colon only
Split into tokens by comma
Check for a range or a single digit
Extract numbers
Set cells accordingly
关于C、从文件输入到二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30835468/