#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define N 5
void readBoard (FILE *fp, char table[N][N], int n){
int i, err, j, counter = 0;
char c;
int row = 0, col = 0, ch = 0;
while((err = fscanf(fp, "%c", &c)) == 1){
if (c!= ' ' && (c == 'o' || c == 'M' || c == '.')){
ch++;
counter++;
if (counter == 5){
counter = 0;
row++;
}
}
if( c != ' ' && c != 'M' && c != 'o' && c!= '.' && c != '\n'){
printf("Error. File is not correct. \n");
exit(EXIT_FAILURE);
}
}
col = ch/row;
if (col != N || row != N){
printf("Error. Incorrect data in file. \n");
exit(EXIT_FAILURE);
}
i = 0;
j = 0;
while((err = fscanf(fp, "%c", &c)) == 1){
if( c!= ' ' && (c == 'o' || c == 'M' || c == '.')){
table[i][j] = c;
j++;
if(j == N-1){
j = 0;
i++;
}
}
}
}
void displayBoard (char table[N][N]){
int r = 0;
int c = 0;
char ch;
for(r = 0; r<N; r++){
for(c = 0; c<N; c++){
printf("%c ", table[r][c]);
}
printf("\n");
}
}
int main(char argc, char *argv[]){
char game[N][N];
char err, c;
FILE *fp;
fp = fopen(argv[1], "r");
if(fp == NULL){
printf("File not found.");
exit(EXIT_FAILURE);
}
readBoard(fp, game, N);
displayBoard(game);
return 0;
}
第一个函数从文件中读取字符,检查它们是否正确并将它们存储到2D数组中。 第二个数组用于打印数组。而不是打印数组,它打印出来:
� � � 2
0
@
p
我不知道出了什么问题。
答案 0 :(得分:0)
第一个循环将读取调用readBoard()
时文件指针所在的所有内容。您必须在第二个循环之前恢复文件指针的位置。
尝试添加
long origPtr = ftell(fp);
在第一个while((err = fscanf(fp, "%c", &c)) == 1){
和
fseek(fp, origPtr, SEEK_SET);
在第二个while((err = fscanf(fp, "%c", &c)) == 1){
之前。