+ 1

Buffers in c

Can someone please explain the concept of buffer in c? And what does it mean to empty the buffer? Why would you do that? How can you do that? I think I needed it once because I wanted to read a string and after that a char but the char would've taken the '\n' value, so no char was read. Instead, I think I had to read the string, empty the buffer and then read the new char. I would like to hear some explanations of this topic. Thank you!

12th Mar 2020, 10:55 AM
pe5te
pe5te - avatar
9 Answers
+ 5
You can easily clear it by using “ while ((getchar()) != ‘\n’); after scanf() statement” , it scans the buffer till newline and discards it. There is an non standard function fflush() also which helps to clear the output buffer but as it is not a standard function so might not sun on some IDEs edit: actually fflush() is a standard function but gives undefined behaviour when used for input stream(thanks ~ swim ~ for pointing it out)
12th Mar 2020, 11:18 AM
Arsenic
Arsenic - avatar
+ 3
Imagine that you're eating candy out of a bowl. You take one piece regularly. To prevent the bowl from running out, someone might refill the bowl before it gets empty, so that when you want to take another piece, there's candy in the bowl. The bowl acts as a buffer between you and the candy bag.
12th Mar 2020, 11:04 AM
Arsenic
Arsenic - avatar
+ 3
On various occasions you may need to clear the unwanted buffer so as to get the next input in the desired container and not in the buffer of previous variable For example, in case of C after encountering scanf() , if we need to input a character array or character, we require to input a character array or a string , we require to clear the input buffer or else the desired input is occupied by buffer of previous variable, not by the desired container.On pressing “Enter" on output screen after the first input , as the buffer of previous variable was the space for new container(as we did’nt clear it) , the program skips the following input of container.
12th Mar 2020, 11:09 AM
Arsenic
Arsenic - avatar
+ 3
OK, and how do we clear it?
12th Mar 2020, 11:13 AM
pe5te
pe5te - avatar
+ 2
Are you asking about the buffer or how to read a char after you read a string? In regards to string, a string buffer in C is the char array, represented by the string variable itself. To empty a string buffer you can set the first character in the string to NULL character (use either '\0' or just 0). P.S. Can you share that code so everyone can check and suggest something? code review is needed to properly respond to the case you are dealing with. Follow this guide on sharing links, in case you didn't know how 👇 https://www.sololearn.com/post/74857/?ref=app
12th Mar 2020, 11:04 AM
Ipang
+ 2
Thank you
12th Mar 2020, 11:24 AM
pe5te
pe5te - avatar
+ 2
~ swim ~ Oops 😅😅 I didn't read the whole answer. I have updated the answer now
12th Mar 2020, 11:45 AM
Arsenic
Arsenic - avatar