+ 6
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? https://code.sololearn.com/cq5gieF6A8mA/?ref=app
7 Antworten
+ 3
Thank you codemonkey
+ 3
codemonkey is it necessary to allocate space for null terminator in char array?
I ask this question because fgets() alone append the null terminator
+ 3
Thank you codemonkey I got it😂
+ 3
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
+ 3
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
https://code.sololearn.com/cC9K438PtS1C/?ref=app
+ 3
Wow it was really a tricky one.😱
Thank you codemonkey ☺
+ 2
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?😅