Can anybody help me out with the right input way? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Can anybody help me out with the right input way?

I have inputted like this 1 7 Y 1 8 Y 3 n, it gives output as 0807 instead of 87 just , https://code.sololearn.com/c8DO6ClGWviV/?ref=app

22nd Apr 2019, 6:29 AM
Abhay
Abhay - avatar
3 Answers
+ 2
Abhay You're welcome. And about the reason for the space: When we enter a menu choice we type a number followed by {Enter} key, also when we type a number to insert a new value into the stack - we type the number and hit {Enter} key. It is the character of that {Enter} key that was left in the input buffer. scanf uses that leftover character when it sees that an input is needed for <option> variable. If we put space before the %c - that leftover character will be ignored (because a space is not a format specifier), and the letter we type ('y' or 'n') will be stored correctly in <option> variable. To confirm this you can test the scanf call for <option> variable like this: scanf("%c", &option); // no space before %c printf("%d", option); // output 10, the ASCII code for {Enter} key I hope this shades a light even just a bit : )
22nd Apr 2019, 2:33 PM
Ipang
+ 3
I think you have written the input in a correct sequence, the problem is in the code. Make a few correction and I guess it'll work well. ● In the switch statement: case 4: break; instead of exit(0); * There's no need to force exit when we can simply exit the menu loop. ● When asking confirmation: scanf(" %c", &option); * Notice the space before the %c specifier, it was necessary because the input stream buffer has a leftover byte from previous input. The leftover byte will be consumed in by the space. ● In the display function: * Do check whether there is any data (top != -1) before going through the loop printing the data. Try to make this changes and let me know how it goes.
22nd Apr 2019, 8:06 AM
Ipang
+ 1
Ipang ,wow the only thing missing was space before that %c ,which I would have never ever able to correct ,thks a lot and I still dunno why that space is really needed ,I have never given a space before % c lol , maybe it's due to the compiler ? or it will give 0 everywhere?
22nd Apr 2019, 2:09 PM
Abhay
Abhay - avatar