gpt4 book ai didi

c - 函数无法在 c 中正确打印

转载 作者:太空宇宙 更新时间:2023-11-04 04:28:09 26 4
gpt4 key购买 nike

我正在尝试构建一个动态迷宫,我到达了获得大小并从中获取构建迷宫所需的字符的部分。但是构建迷宫的函数打印出它确实不对称,我该如何解决?

我的代码:

  #include <stdio.h>
#include <stdlib.h>

char **board;
int size = 0;

void print_Board();
void initialize_Board();

int main()
{
initialize_Board();
print_Board();

return 0;
}

/*initialize the board*/
void initialize_Board()
{
int i, j;//indexs
char s;
scanf("%d", &size);

board = (char**)malloc(sizeof(char*)* (size));
if (!board) { printf("ERROR - memroy allocation.\n"); exit(1); }

for (i = 0; i < size; i++)//for loops to build the board for the game
{
board[i] = (char*)malloc(sizeof(char)*(size));
if (!board[i]) { printf("ERROR - memroy allocation, for loop\n");
exit(1);
}

for (j = 0; j < size; j++)
{
scanf("%c", &s);
board[i][j] = s;
}//for col

printf("\n");

}//for row
}

//print the board
void print_Board()
{
int i, j;

for (i = 0; i < size; i++)
{
for (j = 0; j < size; j++)
{
printf("%c ", board[i][j]); //print the value in the [i][j] place.
}//for col

printf("\n");

}//for row
}

最佳答案

改变:

for (j = 0; j < size; j++)
{
scanf("%c", &s);
board[i][j] = s;
}//for col

收件人:

for (j = 0; j < size; j++) {
scanf("%c ", &s);
board[i][j] = s;
}//for col
board[i][j] = '\n'; // Add new line to end of row making it a string.

这确保读取每个字符并丢弃返回的字符。

和改变:

int i, j;
for (i = 0; i < size; i++)
{
for (j = 0; j < size; j++)
{
printf("%c ", board[i][j]); //print the value in the [i][j] place.
}//for col

printf("\n");

}//for row

到:

int i;

for (i = 0; i < size; i++) {
printf("%s", board[i]); //print the values in the [i] row.
}

这将在每一行的末尾打印一个换行符。

关于c - 函数无法在 c 中正确打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39325698/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com