0
how does the following code work?
my main confusion is about the fact that we are getting a sentence from the user but using a char type of variable instead of a string one. https://www.sololearn.com/compiler-playground/ciyo7rjQMvyi
6 Réponses
+ 2
Link to his code for others on the app: https://code.sololearn.com/ciyo7rjQMvyi/?ref=app
+ 2
I don't think there's anything to explain in your code apart from the fact that it won't work as expected on the playground... I've tried doing interactive stuffs and all input have to be provided once
Orin, can you explain what you mean by "it won't ask for new input untill the existing buffer is empty"?,
I'm thinking stream buffers(I/O) are actually made so they can pile up many operations for efficiency and automatically flushed at the end of main function (if the program did not break unexpectedly) or manually using std::endl or std::flush 🤔
+ 2
The string variable "sen" is used to store the the complete sentence. The char variable "c" is used to store individual characters entered by the user.
+ 1
The use of a char type is so that cin only takes one letter at a time, so you can count them
+ 1
Oh ok I think I understand what you're really asking. This works because cin actually stores the whole line of input in an iostream buffer, and the >> extracts from that buffer.
I thought that this would stop for input each loop outside of the playground, but apparently not, it won't ask for new input until the existing buffer is empty (which apparently causes other headaches if you forget to clear the buffer lol)
+ 1
I can't really speak to it to be honest, haven't looked into how io stream is implemented. I just saw someone complaining on stack overflow about a cin step being skipped (as in not prompting for user input, and not in a sandbox like sololearn playground), and the advice was to purge the buffer, so that's a pretty big clue.