Shutao Tang Shutao Tang - 3 months ago 26
C Question

Why scanf cannot read my input?

I would like use

scanf()
to read the following table:

Q 1 3
U 2 6
Q 2 5
U 4 8


This is my code:

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

void main() {
int *a;
int i, j;

a = (int *) malloc(4 * 3 *sizeof(int));

printf("input:\n");
for (i = 0; i < 4; i++) {
for (j = 0; j < 3; j++) {
scanf("%d", a + 3 * i + j);
}
}

printf("output:\n");

for (i = 0; i < 4; i++) {
for (j = 0; j < 3; j++) {
printf("%d ", a[3*i+j]);
}
printf("\n");
}
}


enter image description here

However, when I input the first line
Q 1 3
, this program end. I don't know why?

Answer

This happens because you provided a non-numeric input to your program that wants to read a number with %d. Since Q is not a number, scanf fails.

However, your program is not paying attention to the return value of scanf, and keeps calling it in the failed state. The program thinks that it is getting some data, while in fact it does not.

To fix this, change the code to pass %c or %s when it reads the non-numeric character, check the return value of scanf, and get rid of invalid input when scanf fails.

When you call scanf, it returns how many values corresponding to % specifiers it has provided. Here is how to check the return value of scanf:

if (scanf("%d", a + 3 * i + j) == 1) {
    ...                   // The input is valid
} else {
    fscanf(f, "%*[^\n]"); // Ignore to end of line
}
Comments