Question related to fgets() | SoloLearn: Learn to code for FREE!


Question related to fgets()

I want to store a string of length two, in a char array. I use the fgets() to get a user input (by setting maximum limit as two) When I tend to output that string But it output only one character. Why?

8/1/2020 6:32:14 AM


7 Answers

New Answer


Thank you codemonkey


codemonkey is it necessary to allocate space for null terminator in char array? I ask this question because fgets() alone append the null terminator


Thank you codemonkey I got it😂


codemonkey how did you find that // Also, fgets() is a bit tricky: char arr[3]; fgets(arr, 3, stdin); If user inputs only one character 'a' and hits enter, fgets will read character 'a', read the new line and then append null terminator. Your string will look like this: arr = {'a' , '\n' , '\0'} // Can you provide some code for that to understand clearly


codemonkey I don't see(i.e didn't take place) "\n" newline 😂 in my output when I enter "a" alone based on your comment


Wow it was really a tricky one.😱 Thank you codemonkey ☺


codemonkey suppose if run this code #include <stdio.h> int main() { char char_array[3]; fgets(char_array,3, stdin); printf("%s",char_array);; return 0; } If we input nothing then the output was considered as \n \n \0 // in ansii code 1010 Am I right code monkey?😅