我試圖讀取一個給定的檔案并將其行數寫入一個陣列。起初,我沒有動態分配變數(maze)來存盤檔案的行。這是我到現在為止的code。
#include <stdio.h>/span>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
char c, maze[300][300], buffer[1000] = {''/span>};
int ch = 0, column, row, columns = 0, rows = 0。
FILE* file = fopen(" boards/0.txt", "r ")。
if ( file )
{
while( fgets(buffer, sizeof(buffer), file) != NULL)
rows =1。
}
//rows將計算行的數量。
else[/span
{
printf("沒有此類檔案。
")。)
exit(1)。
}
// and columns will count the number of columns.
columns = (strlen(buffer) - 1)。
//將內容檔案寫入Matriz中。
for (row = 0; row < rows ; row )
{
for (column = 0; column < columns; column )
{
if(fscanf(file, "%c", &maze[row][umn]) !=1)
exit(1)。
}
}
fclose(file)。
//列印行數 //列印行數
for (row = 0; row < rows; row )
{
for (column = 0; column < columns; column )
{
printf("%c",maze[row][column])。
}
}
return 0;
}
這是輸入檔案:
....*.....................
..........................
........*........*........
.....*....................
...............*....*.....
..*.......*...............
............*.............
..........................
..............*...........
..................*.......
..*.......*......*........
....*..*..................
...**.....................
..........*...............
....................*.....
..........................
....**....................
......................*...
輸出應該是一樣的,但什么也沒有發生。我知道我應該動態分配的陣列,但我不確定如何將其納入代碼以使其作業。
uj5u.com熱心網友回復:
你的解決方案的主要問題是,你在完成第一次讀取后沒有重置檔案的位置。
你應該在第二次讀取之前使用fseek(file, SEEK_SET, 0)。
另一個問題是你用fscanf將換行字符讀到了一個迷宮的位置,我想你并不希望這樣:)
你可以一次完成這個程序:
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char maze[300][300] = { 0 };
int column = 0, row = 0, columns = 0, rows = 0;
FILE* file = fopen(" boards/0.txt", "r")。
if (file) {
while (fgets(&maze[rows][0], 300, file) != NULL) {
rows ;
}
columns = strlen(&maze[0][0] ) - 1;
} else {
printf("There's no such file.
")。)
return 1;
}
fclose(file)。
// print rows
for (row = 0; row < rows; row ) {
for (column = 0; column < columns; column ) {
printf("%c", maze[row][column])。
}
printf("
")。)
}
return 0;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/332254.html
標籤:
上一篇:用express和nodeJS在嵌套的API呼叫中處理錯誤
下一篇:從用戶那里獲取字串作為輸入
