Answer the question
In order to leave comments, you need to log in
How to deal with the function of reading a string?
The book provides the following function to read a line from standard input.
I can't understand her logic.
It turns fgets(str, size, stdin);
out means to read into the buffer a string of size size
including the newline character \n
.
Then in the loop it turns out we run through the entire line in search of the index of the character \n
or \0
. Here it is not clear where the null character can come from, if in any case, when entering from the terminal, there will be a newline character at the end.
Next comes the check if the found character is a newline character, then we replace it with a null character, leaving this string without a newline character. But again, the logic is not clear else
. Again, where can the null character come from before the newline character, and in principle I can’t understand where it can come from.
And it is not clear why the next cycle of skipping characters after \0
before \n
.
while (getchar() != '\n')
continue;
char * s_gets(char * str, size_t size)
{
char * return_value;
int i = 0;
return_value = fgets(str, size, stdin);
if (return_value)
{
while (str[i] != '\n' && str[i] != '\0')
i++;
if (str[i] == '\n')
str[i] = '\0';
else
while (getchar() != '\n')
continue;
}
return return_value;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question