-
Damn stack!!
I wrote up a little console program and the darn thing don't work properly.
It scans for a keybord input using scanf. Only, when I enter a proper value and press enter, it does not go to the next step. I have to input another value and press enter again. This time it works but the second value I inputed is passed to the second question. The value I entered for the second question is passed to the third question and so on.
Really annoying.
I'm sure somebody can help me?
-
-
scanf does that because it leaves stuff in the input buffer, when you go for the next read everything in the buffer will be read instead of what you type. Use getchar to get rid of that.
Code:
int main(){
int x, y;
printf("read one");
scanf("%d", &x);
getchar();
printf("read two");
scanf("%d", &y);
printf("%d %d", x, y);
return 0;
}
-Prelude
-
LOL Prelude it's that scanf function again.
at the risk of sounding boring I'm gonna say it again NEVER use scanf, for the reason Prelude gave.
Theres always an alternative which may mean extra coding but will be far safer.
:D
-
There's always an alternative to scanf, it's always better, but schools only teach scanf for some stupid reason :P
-Prelude
-
Furthermore...
Here is the code I wrote :
printf("\n\nEnter the Young's longitudinal modulus for the fibers in GPa :\n");
scanf(" %f ", &e1f);
printf("\nYoung's longitudinal modulus for the fibers is %4.2f GPa.\n", e1f);
printf("\nEnter the Young's transverse modulus for the fibers in GPa :\n");
scanf(" %f ", &etf);
printf("\nYoung's tranverse modulus for the fibers is %4.2f GPa.\n", etf);
printf("\nEnter the shear modulus for the fibers in GPa :\n");
scanf(" %f ", &g12f);
printf("\nShear modulus for the fibers is %4.2f GPa.\n", g12f);
printf("\nEnter the major Poisson's ration for the fibers :\n");
scanf(" %f ", &poissonf);
printf("\nMajor Poisson's ration for the fibers is %.3f.\n", poissonf);
printf("\nEnter the Young's modulus for the matrix in GPa :\n");
scanf(" %f ", &em);
printf("\nYoung's modulus for the matrix is %4.2f GPa.\n", em);
printf("\nEnter the Poisson's ration for the matrix :\n");
scanf(" %f ", &poissonm);
printf("\nMajor Poisson's ration for the matrix is %.3f.\n", poissonm);
printf("\nEnter the fiber volume fraction to be used for all of the plies :\n");
scanf(" %f ", &fibvol);
printf("\nThe fiber volume ratio for the laminate is %4.3f.\n", fibvol);
I tried getchar() after scanf as you suggested Prelude. It works only now I have to press [enter], a number and [enter] for each question. It seems as though scanf cannot detect the end of input on the first [enter].
-
Yet another reason to not use scanf. Look up functions such as fgets, getchar, and fgetc. Those are good replacements.
-Prelude
-
Thanks Prelude.
I used fgets with string conversion functions and now my code works like a charm.