有谁能向我解释如何使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;
}控制台只抛出一堆随机数..。
发布于 2015-06-15 00:50:22
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
enum { EOD = -1, EOL = -2, ERR = -3, OFF = 0, ON = 1 };//End Of Data, End Of Line
int getValue(FILE *fp){
static int on_yield = OFF, prev, end;
if(on_yield == ON && prev < end){
return ++prev;
}
on_yield = OFF;
int n, ch = fgetc(fp);
if(ch == EOF)
return EOD;
else if(ch == ';')
return EOL;
else if(ch == ',' || ch == '\n')
return getValue(fp);//or change to using loop
else if(isdigit(ch)){
ungetc(ch, fp);
fscanf(fp, "%d", &n);
return prev=n;
} else if(ch == '-'){
on_yield = ON;
fscanf(fp, "%d", &n);
end = n;
return getValue(fp);
}
fprintf(stderr, "(%c) invalid format in file\n", ch);
return ERR;
}
int main(void){
FILE *ptr_file = fopen("data.txt", "r");
if(!ptr_file){
perror("fopen");
return 1;
}
int size;
fscanf(ptr_file, "%d", &size);//check omitted
char (*cell)[size] = malloc(size * sizeof(*cell));
memset(&cell[0][0], ' ', size*size);
int r = 0, c, value;
while((value=getValue(ptr_file))!=EOD){
if(value == EOL){
++r;
continue;
}
if(value > 0)
cell[r][value-1] = '*';
}
fclose(ptr_file);
for(r = 0; r < size; ++r){
for(c = 0; c < size; ++c){
putchar(cell[r][c]);
}
putchar('\n');
}
free(cell);
return 0;
}发布于 2015-06-14 23:28:47
伪码:
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发布于 2015-06-15 00:04:10
“随机”数字是文件中的字节值,您忘了在行尾停止。Dave的解决方案不太适合c。在读了一行之后:
while not semicolon
strtoul a number
if no number
exit error
if next char is hyphen
shift to next char
strtoul end of range
if no number
exit error
set cells
else
set cell
if next char is not semicolon
shift to next char你不应该用阿托伊做任何事。使用sscanf或strto…。
https://stackoverflow.com/questions/30835468
复制相似问题