我正在用C寫一個程序來解決迷宮遊戲。輸入迷宮文件將從標準輸入讀取。我寫了下面的程序,它從stdin讀取迷宮並打印沒有。行和列。但是,一旦我完全讀取我的輸入文件,我怎麼才能再次訪問它,以便我可以執行下一步?如何從stdin多次讀取stdin中的數據
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define BUFFERSIZE (1000)
struct maze {
char ** map;
int startx, starty;
int numrows;
int initdir;
};
void ReadMaze(char * filename, struct maze * maze);
int main(int argc, char *argv[]) {
struct maze maze;
ReadMaze(argv[1], &maze);
return EXIT_SUCCESS;
}
/* Creates a maze from a file */
void ReadMaze(char * filename, struct maze * maze) {
char buffer[BUFFERSIZE];
char mazeValue [BUFFERSIZE][BUFFERSIZE];
char ** map;
int rows = 0, foundentrance = 0, foundexit = 0;
int columns = 0;
/* Determine number of rows in maze */
while (fgets(buffer, BUFFERSIZE, stdin)){
++rows;
puts(buffer);
columns = strlen(buffer);
}
printf("No of rows: %d\n", rows);
printf("No of columns: %d\n", columns);
if (!(map = malloc(rows * sizeof *map))) {
fputs("Couldn't allocate memory for map\n", stderr);
exit(EXIT_FAILURE);
}
}
您可以更改文件的格式,以迷宮大小的兩個值(寬度和高度)開始,然後是迷宮數據?這樣,你只需要一次傳遞文件。 –