【问题标题】:function not printing correctly in c函数无法在 c 中正确打印
【发布时间】:2016-09-05 07:29:26
【问题描述】:

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

我的代码:

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

【问题讨论】:

  • 介意发布示例输出吗?
  • 是否考虑过发布MCVE
  • 一种猜测是您在每一行后按 Enter,这会被 scanf 读取为额外字符。
  • scanf("%c", &amp;s); --> scanf(" %c", &amp;s);
  • BLUEPIXY 谢谢!修复它!

标签: c arrays maze ansi-c


【解决方案1】:

变化:

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

这会打印每一行,并在末尾添加一个换行符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 2016-01-22
    • 2021-01-16
    • 1970-01-01
    相关资源
    最近更新 更多