Whats wrong with char input for this 2 dimensional char array? why its not taking total of K*K inputs?

StackOverflow https://stackoverflow.com/questions/13112397

  •  14-07-2021
  •  | 
  •  

Pergunta

I am trying to take 2 dimensional char data from user, but it's not taking input from user properly. Could you highlight the bug in following code?

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

int main()
{
int i, j, k;
char **ch;

printf("\nEnter k : ");
scanf("%d",&k);

ch = (char **) malloc (sizeof(char*) * k );
if(ch == NULL) { printf("\n Not enough memory for ch array "); exit(0);}
for(i = 0; i < k; i++)  {
    ch[i] = (char *) malloc (sizeof(char) * k );
    if(ch[i] == NULL) { printf("\n Not enough memory for ch array "); exit(0);}
}

printf("\nenter char matrix ( %d X %d )\n", k,k);
for(i = 0; i < k; i++) {
    for(j = 0; j < k; j++) {
        scanf("%c", (*(ch + i) + j) );
    }
}

printf("\n char matrix : \n");
for(i = 0; i < k; i++) {
    for(j = 0; j < k; j++) {
        printf("%c ",*(*(ch + i) + j));
    }
    printf("\n");
}

for(i = 0; i < k; i++)  free(*(ch + i));
free(ch);   
return 0;
}

I tried replacing char by int. It does work fine for integers.

What's wrong with char reading from stdin?

Foi útil?

Solução

Problem:

scanf("%c", (*(ch + i) + j) );

after scanf("%d",&k); there's still a newline in the input buffer, that becomes the first entry of the char matrix. If you enter further newlines while filling the matrix, they become matrix entries too.

Clear the input buffer before filling the matrix.

int c;
do {
    c = getchar();
}while(c != '\n' && c != EOF);
if (c == EOF) {
    // input stream broken, yell
}

Outras dicas

Experiment with this little program until you're comfortable with scanf(). Learn about getchar() and newlines.

#include <stdio.h>

int main(int argc, char **argv) {
    char a,b,c;
    scanf("%c", &a);
    scanf("%c", &b);
    scanf("%c", &c);
    printf("a='%c', b='%c', c='%c'\n", a, b, c);
    return 0;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top