我想通過外部加載的檔案在 int maze[ROW][COL] 函式中創建一個陣列。
int main 中 text.txt 中的內容
111111111111111111111111
100111111111111110111111
110000111111110000001111
110110111111110110110111
110011000000110110110111
111011111110110110110111
111011111110000111110111
111000001111111111110111
111111101111111110000111
111111101110000000111111
100000011110111111111111
111111111110000000000001
111111111111111111111111
我發布了我的代碼的一部分來幫助解釋。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define ROW 13
#define COL 24
#define STACK_SIZE ROW * COL
#define TRUE 1
#define FALSE 0
int maze[ROW][COL] = {
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1},
{1,1,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,1,1,1},
{1,1,0,1,1,0,1,1,1,1,1,1,1,1,0,1,1,0,1,1,0,1,1,1},
{1,1,0,0,1,1,0,0,0,0,0,0,1,1,0,1,1,0,1,1,0,1,1,1},
{1,1,1,0,1,1,1,1,1,1,1,0,1,1,0,1,1,0,1,1,0,1,1,1},
{1,1,1,0,1,1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,0,1,1,1},
{1,1,1,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1},
{1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,1},
{1,1,1,1,1,1,1,0,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1},
{1,0,0,0,0,0,0,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
};
省略的代碼包括尋路代碼和輸出代碼。
int main(void)
{
printf("<<<INPUT MAZE>>>\n");
FILE* fp = fopen("maze.txt", "r");
char c;
while ((c = fgetc(fp)) != EOF) {
printf("%c", c);
}
printf("\n");
for (i = 0; i < ROW; i )
{
for (j = 0; j <= COL; j )
{
mark[i][j] = 0;
}
}
path();
print_path();
return 0;
}
我嘗試上傳代碼,但失敗并出現錯誤。對不起。
uj5u.com熱心網友回復:
假設您想maze從檔案
中加載陣列的元素,maze.txt而不是如發布的代碼中所示進行分配,請嘗試以下片段:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define _CRT_SECURE_NO_WARNINGS
#define ROW 13
#define COL 24
#define TRUE 1
#define FALSE 0
#define BUF 256 // line buffer size
#define MAZE "maze.txt" // filename to read
int main(void)
{
FILE *fp;
char buf[BUF];
int maze[ROW][COL];
int i, j;
printf("<<<INPUT MAZE>>>\n");
if (NULL == (fp = fopen(MAZE, "r"))) {
fprintf(stderr, "Can't open %s\n", MAZE);
exit(1);
}
for (i = 0; i < ROW; i ) {
if (! fgets(buf, BUF, fp)) {
fprintf(stderr, "Too few lines in %s\n", MAZE);
exit(1);
}
if (strlen(buf) <= COL) {
fprintf(stderr, "Too few columns in %s\n", buf);
exit(1);
}
for (j = 0; j < COL; j ) {
maze[i][j] = buf[j] == '0' ? FALSE : TRUE;
}
}
// check if the array is properly assigned
for (i = 0; i < ROW; i ) {
for (j = 0; j < COL; j ) {
printf("%d", maze[i][j]);
}
printf("\n");
}
// put your remaining code here
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/460622.html
