繁体   English   中英

功能无法在c中正确打印

[英]function not printing correctly in c

我正在努力构建一个动态的迷宫,我得到的部分,我得到的大小,并获得我需要从他们建立迷宫的字符。 但构建迷宫的功能打印它真的不对称我该怎么解决?

我的代码:

  #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.
}

这将在最后打印每行一个换行符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM