I am developing a simple compiler in the cygwin environment using flex and bison generating C code as output and I have generated a sequence of code intended to read two integers followed by a char.
Whereas I thought I knew basic c code I am suffering a problem with the code below where I input two integers, but it never asks for the character after reading the integers!
What is the best way to handle generating code like this, should I always clear the character buffer before performing a scan or a getchar() or have i just made a mistake somewhere!!!
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
int a = 0;
int b = 0;
char f = '\0';
scanf("%d",&a);
scanf("%d",&b);
f = getchar();
fflush( stdin );
return EXIT_SUCCESS;
}
If you want to read each part of the input on a new line, change your
scanfformat string so that it consumes the'\n', since at the momentf = '\n'. ie. use"%d\n"instead of"%d".And then you can print the values to make sure (
printf("a: %d, b: %d, f: %c\n", a, b, f);)An alternative is also to replace the two
scanfstatements and thegetcharwith a singlescanfstatement:scanf("%d\n%d\n%c", &a, &b, &f);.