I am struggling to figure out why my scanf()
is reading a white space character. I have searched and found the problem can be fixed by adding a space between the quotation and %c
. Example:
scanf(" %c..);
However, this does not solve my problem.
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h>
int main(void) {
char ch, ch1, ch2, ch3, ch4;
ch = 'a';
unsigned short int;
double b = INFINITY;
short u;
char c;
float f;
printf("%c\n", ch);
printf("%d\n", ch);
printf("%d\n", SHRT_MAX);
printf("%lf\n", b);
printf("Enter char int char float: \n");
scanf("%c %d %c %f", &ch1, &u, &ch2, &f); // This line reads correctly. Ex.
// a 5 b 5.5
printf("You entered: %c %d %c %0.3f\n", ch1, u, ch2, f);
printf("Enter char float int char: \n");
scanf(" %c %f %d %c", &ch3, &f, &u, &ch4); // This line reads 5.5 5 a
// Here is where the first %c
// is being read as a white space.
printf("You entered: %c %0.3f %d %c\n", ch3, f, u, ch4);
return 0;
}
Edit Here is what I am getting.
a
97
32767
1.#INF00
Enter char int char float:
a 5 b 5.5
You entered: a 5 b 5.500
Enter char float int char:
c 5.5 5 d
You entered: 5.500 5 d
Process returned 0 (0x0) execution time : 11.929 s
Press any key to continue.
Edit #2
I have tried the following - all resulting in the same output.
printf("Enter char int char float: \n");
scanf("%c %d %c %f", &ch1, &u, &ch2, &f);
printf("You entered: %c %d %c %0.3f\n", ch1, u, ch2, f);
fflush(stdin);
printf("Enter char float int char: \n");
scanf(" %c %f %d %c", &ch3, &f, &u, &ch4);
printf("You entered: %c %0.3f %d %c\n", ch3, f, u, ch4);
Edit #3
Here is a more concise version of my problem.
printf("Enter char int char float: \n");
scanf("%c %d %c %f", &ch1, &u, &ch2, &f); // This line reads correctly. Ex.
// a 5 b 5.5
printf("You entered: %c %d %c %0.3f\n", ch1, u, ch2, f);
printf("Enter char float int char: \n");
scanf(" %c %f %d %c", &ch3, &f, &u, &ch4); // This line reads 5.5 5 a
// Here is where the first %c
// is being read as a white
// space. I am expecting there
// to be a character here. Not
// a white space. See Edit #1
// for output results.
printf("You entered: %c %0.3f %d %c\n", ch3, f, u, ch4);
return 0;
}