i'm having a litle trouble with input info on a matrix
i want to build a simple wordsearch game. The user tells the dimension of the matrix to the wordsearch and inputs the characters and i want to print it just to see if everything is okey with the info.
This is my code:
void main (){
int nl, nc, i,j;
scanf ("%d %d", &nl,&nc); //Input number of lines and collums of the matrix
char matrix [nl] [nc];
for (i=0;i<nl;i++)
for (j=0;j<nc;j++)
scanf("%c",&matrix[i][j]); //Input matrix
printf("This is your matrix:\n");
for (i = 0; i < nl; i++)
for (j = 0; j < nc; j++)
printf("%c", matrix [i][j]);
}
If i input something like
2 3
ABC
DEF
The output should be:
This is your Matrix:
ABC
DEF
But my output when i print is something like
This is your Matrix:
ABC
D
It first gives a "\n" then prints but not complete.
What am i doing wrong? Please take in consideration that i should only be using functions like scanf and getchar to build the matrix.
OP: "What am i doing wrong?"
A: scanf("%c", ..
is reading '\n'
left over from the previous scanf ("%d%d"...
To avoid that and other white-spaces, consume them by pre-pending a ' '
in the "%c"
format.
1) Check scanf()
results.
2) Use Space before "%c"
to consume whitespace, especially the previous line's \n
.
3) Use main()
correctly.
4) Better to use fputs() or puts() when simply printing a string
Edit: Meet ability to enter a scant line
#include<stdio.h>
#include<stdlib.h>
void ConsumeToEOL(void) {
int ch;
do {
ch = getchar();
} while (ch != '\n' && ch != EOF);
}
int main() {
int nl, nc, i, j;
// Space between "%d %d" not really needed
if (scanf("%d%d", &nl, &nc) != 2) {
fputs("Bad number Input\n", stdout);
exit(1);
}
ConsumeToEOL();
char matrix[nl][nc];
for (i = 0; i < nl; i++) {
for (j = 0; j < nc; j++) {
int ch = getchar();
if (ch == '\n' || ch == EOF)
break;
matrix[i][j] = (char) ch;
}
if (j == nc) ConsumeToEOL();
for (; j < nc; j++) {
matrix[i][j] = 0;
}
}
// Better to use fputs() or puts() when simply printing a string
fputs("This is your matrix:\n", stdout);
for (i = 0; i < nl; i++) {
for (j = 0; j < nc; j++) {
if (matrix[i][j]) {
printf("%c", matrix[i][j]);
}
}
// Add EOL
fputs("\n", stdout);
}
return 0;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments