2

Code:

printf("Enter your data (5x10) of characters: \n");
for (i = 0; i < SIZE1; i++)
for (j = 0; j < SIZE2; j++)
    scanf("%c", &matrix2[i][j]);
compress(matrix2);
break;

My code is suppose to take in a 5 x 10 matrix of char. But currently my newline is being input into the matrix, how do I actually check for the newline char, and prevent it from going into matrix2[i][j]?

It reads a total of 4 newline char. Input:

aaabbbcccd (press enter)
ababababab (press enter)
bcdbcdbcdb (press enter)
ababababab (press enter)
abbbcccdda
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
Jordan Iatro
  • 289
  • 3
  • 10

4 Answers4

6

You can add a space before your %c specifier, like this

scanf(" %c", &matrix2[i][j]);

The blank space here in the format string is telling scanf() to skip any leading whitespace or newline character, thus consuming the next character typed with the %c conversion specifier.

Your situtation is happening because when you (press enter), the next scanf() call is consuming this newline character \n that was left behind, therefore making your statement fail.

Natan Streppel
  • 5,759
  • 6
  • 35
  • 43
4

Add a space:

scanf(" %c", &matrix2[i][j]);
       ^

The space (unintuitively) consumes any white-space, including the \n. But this change means you can't put a space into matrix, which may or may not be what you want.

But it is generally better to use e.g. fgets() and sscanf() rather than scanf() to parse input.

Joseph Quinsey
  • 9,553
  • 10
  • 54
  • 77
  • 1
    but suppose if OP use fgets then space chars will be stored in matrix[], I think you should suggest first read input in a buffer then parse it to store in matrix[] – Grijesh Chauhan Mar 19 '14 at 04:04
2
char matrix2[SIZE1][SIZE2];
int ch, count, end, i, j;
char  *p = &matrix2[0][0];

printf("Enter your data (5x10) of characters: \n");
count = 0; end = SIZE1 * SIZE2;
while (EOF!=(ch=fgetc(stdin)) && count < end){
    if(ch == '\n')
        continue;
    p[count++] = ch;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
1

you can store the i/p character in a dummy variable and then check if it is a space or a /n . ie.

printf("Enter your data (5x10) of characters: \n");
for (i = 0; i < SIZE1; i++)
for (j = 0; j < SIZE2; j++)
{
  d:  scanf("%c", &a);
      if(a!=' '||a!='\n')
          matrix2[i][j]=a;
      else
          goto d;
}

compress(matrix2);
break;
Bas
  • 469
  • 8
  • 22