0
geatting proble with scanf in while loop
Hi friend Here I have given the link of my code I am reading integer value in run time. so if I give integer it is printing and if I give any alphabet it is continuously executing else condition. Please let me know the change. Thank you https://code.sololearn.com/cWoBrc9Dc7ZK
7 Réponses
+ 2
Your variables i and j are both of type integer then how can they accept a value that is a character.
+ 2
Remove tilt '~' from last line and program will cause infinite loop with any number. Coz while(1) which will always be true.
Edit: And sololearn doesn't support dynamic input means you can't stop the execution of program in sololearn once you give input in input pop up.
And yes with %d specifier you can only give integer not any other value.
+ 1
Scanf will return count of the inputs it has read(if the given input matches with format specifier). So here if I give integer value as an input, then scanf returns 1. Other than that it returns 0. If I give input a, a is character. So scanf returns 0. Again loop rotate and here scanf taking input as a only. I think it is storing in buffer. I tried to clear buffer using fflush(stdin). But that data in buffer is not getting clear. I understood this is the problem. Could you give any suggestion please.
+ 1
Thank you swim ...I think my doubt might not be proper previously.
+ 1
You are entering character in place of integer.
Computer store data as a value according to ascii value.
When you enter character compiler do casting from char to int.
So you will get ascii value of character in you enter
And thus code runs without any error.
+ 1
It's simple, first of all:
1) The expression `j = scanf("%d",&i);` assigns the value 1 to j. This is because Scanf will return count of the inputs it has read. So you should do `j = i;` after calling `scanf("%d", &i)`.
2) Another error (the infinite loop) is due to the web interface. Try it in your machine, it should work fine.
3) Next error (infinite loop in local machines when a char/string is entered) happens due to the invalid input datatype. So you should put `getchar();` after in else block. This will say the compiler to wait for the user input.
4) Though it's not a problem, it is a good practice to use curly braces after if even if it's a one-liner.