how does the following code work? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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

8th Jun 2023, 7:05 PM
Faran Allah Verdi
Faran Allah Verdi - avatar
6 Answers
+ 2
Link to his code for others on the app: https://code.sololearn.com/ciyo7rjQMvyi/?ref=app
8th Jun 2023, 7:18 PM
Orin Cook
Orin Cook - avatar
+ 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 🤔
9th Jun 2023, 1:00 AM
White Shadow
White Shadow - avatar
+ 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.
11th Jun 2023, 11:21 PM
Chris Coder
Chris Coder - avatar
+ 1
The use of a char type is so that cin only takes one letter at a time, so you can count them
8th Jun 2023, 7:23 PM
Orin Cook
Orin Cook - avatar
+ 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)
8th Jun 2023, 7:34 PM
Orin Cook
Orin Cook - avatar
+ 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.
9th Jun 2023, 1:06 AM
Orin Cook
Orin Cook - avatar