打印时,我的2D数组中有一个缺少的元素

时间:2021-01-09 21:37:42
#include<stdio.h>
#include<stdlib.h>
#define MSIZE 10
int main()
{
    int Size, gen, i, j;
    printf("Enter number of generations\t");
    scanf("%d", &gen);
    printf("\nEnter size of the matrix (max size is %d and min is 2)\t", MSIZE);
    scanf("%d", &Size);
    if (Size > MSIZE)  {
        printf("\nSize should not be more than %d", MSIZE);
        return 1;
    }
    if (Size < 2)  {
        printf("\nSize should not be less than 2");
        return 1;
    }
    char **m = (char**) calloc(Size, sizeof(char*));
    for (i=0; i<Size; i++)
    {
        m[i] = (char*) calloc(Size, sizeof(char));
    }
    printf("Enter matrix of first generation\n");
    for (i=0; i<Size; i++)  {
        for (j=0; j<Size; j++)  {
            scanf("%c", &m[i][j]);
            /*to make sure*/
            printf("%c ", m[i][j]);
        }
        printf("\n\n");
    }
}

This is the first part of my program which should be about the death game for Conway. I think, the problem is in the input function, because if I fill it inside the program by myself (not by input) it will be printed right.

这是我的计划的第一部分,应该是关于康威的死亡游戏。我认为,问题出在输入函数中,因为如果我自己将它填入程序内部(而不是输入),它将被正确打印。

1 个解决方案

#1


2  

I think, the problem is in the input function, because if I fill it inside the program by myself (not by input) it will be printed right.

我认为,问题出在输入函数中,因为如果我自己将它填入程序内部(而不是输入),它将被正确打印。

You need a space before "%c" in scanf() to consume a previous newline/enter:

在scanf()中“%c”之前需要一个空格来使用前一个换行符/输入:

for (i=0; i<Size; i++)  {
    for (j=0; j<Size; j++)  {
        scanf(" %c", &m[i][j]);
        /*to make sure*/
        printf("%c ", m[i][j]);
    }
    printf("\n\n");
}

When you hit enter on the previous scanf(), a newline is placed in the input buffer. Adding a space in front of %c tells scanf() to skip that newline (and other whitespace).

当您在上一个scanf()上按Enter键时,会在输入缓冲区中放置换行符。在%c前面添加一个空格告诉scanf()跳过该换行符(和其他空格)。

#1


2  

I think, the problem is in the input function, because if I fill it inside the program by myself (not by input) it will be printed right.

我认为,问题出在输入函数中,因为如果我自己将它填入程序内部(而不是输入),它将被正确打印。

You need a space before "%c" in scanf() to consume a previous newline/enter:

在scanf()中“%c”之前需要一个空格来使用前一个换行符/输入:

for (i=0; i<Size; i++)  {
    for (j=0; j<Size; j++)  {
        scanf(" %c", &m[i][j]);
        /*to make sure*/
        printf("%c ", m[i][j]);
    }
    printf("\n\n");
}

When you hit enter on the previous scanf(), a newline is placed in the input buffer. Adding a space in front of %c tells scanf() to skip that newline (and other whitespace).

当您在上一个scanf()上按Enter键时,会在输入缓冲区中放置换行符。在%c前面添加一个空格告诉scanf()跳过该换行符(和其他空格)。