Reputation:
I have two questions regarding the following C code.
clear()
in the code? I thought
it was so I could press enter to "stop" entering the 11 characters
required for myarray
, but it seems I could do that for the
suceeding scanf
calls as well.fgets
always close the buffer with "\n"? What if I put 11
characters instead of ten? How would the function know to end the
character with "\n"?#include <stdio.h>
void clear ()
{
while ( getchar() != '\n' );
}
int main() {
int value;
unsigned int second;
char myarray[11];
printf("Enter 10 characters:");
fgets(myarray, 11, stdin);
clear();
printf("Enter an integer between -50,000 and 50,000:");
scanf("%d",&value);
printf("Enter an unsigned integer between 0 and 100,000:");
scanf("%ud",&second);
...
Upvotes: 1
Views: 91
Reputation: 23792
What is the purpose of clear() in the code?
The purpose of clear()
is to remove all the remaining charaters in the stdin
buffer, in case the inputed string is bigger than 11 - 1
.
Does fgets always close the buffer with "\n"? What if I put
11
characters instead of ten?
It does not, if the input stream has the size of 11
characters or bigger, only 11 - 1
will be read, the 11th
character and those above are never read, leaving a space in myarray[]
for the '\0'
null terminator, they will remain in the buffer as will '\n'
, hence the need for clear()
.
Example:
If inputed string is "qwertyuiopa"
, q w e r t y u i o p \0
will be your char array, a \n
will remain in the stdin
buffer.
How would the function know to end the character with "\n"?
fgets
stops reading as soon as the 11th - 1
character is read, as determined by its second parameter, regarldless of what character, or if '\n'
is found, in witch case all the characters are read, including '\n'
, and will be stored in myarray[]
.
Example:
Inputed "qwerty"
, char array will be q w e r t y \n \0
, stdin buffer will be empty.
One last note, for total correctness, the clear()
function should account for EOF
:
int c;
while((c = getchar()) != '\n' && c != EOF);
Upvotes: 1