Jordan Iatro
Jordan Iatro

Reputation: 297

Checking of Newline char in input

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

Upvotes: 2

Views: 167

Answers (4)

BLUEPIXY
BLUEPIXY

Reputation: 40155

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;
}

Upvotes: 2

Bas
Bas

Reputation: 477

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;

Upvotes: 1

Natan Streppel
Natan Streppel

Reputation: 5866

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.

Upvotes: 6

Joseph Quinsey
Joseph Quinsey

Reputation: 9972

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.

Upvotes: 4

Related Questions