trouble reading a 2D array of characters in C?
This is the code:
#include <stdio.h>
#include <stdlib.h>
void acceptMaze(char maze[ROW][COLOUMN], int nrows, int ncols)
{
int i,j;
for (i = 0; i < nrows; i++)
{
fprintf(stdout,"I = %d",i);
for (j = 0; j < ncols; j++)
{
fprintf(stdout,"J = %d",j);
开发者_运维百科 scanf("%c",&maze[i][j]);
}
}
}
wel while entering data it saysi =0 j=0j=1
.So you see the j=0 doesn't remains.I am using a linux system .Can anyone fix this.
Your problem stems from the fact that the %c
conversion specifier doesn't skip whitespace. If there's a newline stuck in the input stream from a previous input operation, the scanf
call will read that and assign it to maze[i][j]
.
Here's one workaround:
#include <ctype.h>
...
for (i = 0; i < nrows; i++)
{
for (j = 0; i < nrows; j++)
{
int c;
do c = getchar(); while (isspace(c));
maze[i][j] = c;
}
}
The line do c = getchar(); while (isspace(c))
will read input characters until you hit a non-whitespace character.
EDIT
Ugh, I just realized one ugly flaw of this scheme; if you want to a assign a whitespace character like a blank to your maze, this won't work as written. Of course, you can just add to the condition expression:
do c = getchar(); while (isspace(c) && c != ' ');
You need to output some newlines to make it easier for the user to read. How about:
#include <stdio.h>
#include <stdlib.h>
void acceptMaze(char maze[][],int nrows,int ncols)
{
int i,j;
for(i=0;i<nrows;i++)
{
for(j=0;j<ncols;j++)
{
printf("\nenter %d,%d: ",i, j);
scanf("%c",&maze[i][j]);
}
}
}
The enter key is being accepted as input for half of your queries. Say you prompt for i = 0, j = 0, and the user enters '5' followed by the enter key. Scanf inserts '5' into maze[0][0], and in the next iteration of the loop, it sees that the enter key is still in the buffer, so it inserts that into maze[0][1].
You need to flush the input after every scanf. One solution is to #include <iostream>
and call std::cin.ignore()
after each scanf.
精彩评论