fgets在输入末尾添加\ 0或\ n吗? [英] fgets adds \0 or \n at the end of the input?
问题描述
我对fgets有一些疑问.据我所知,它在字符串的末尾添加了"\ n",而不是"\ 0".因此,如果我编写这段代码:
I've some doubts about fgets. From what I know, it adds "\n" at the end of the string, and not "\0". So if I write this code:
fgets(buff,2,stdin);
printf("%s",buff);
因此fgets读取两个字符,我将输入"y"作为输入,因此buff应该为"y \ n".我希望printf打印y并添加一行,而它打印"y"而不添加一行.你能解释为什么吗?
So fgets reads two characters, I give as input "y", so buff should be "y\n". I'd expect printf to print y and add a line, while it prints "y" without adding a line. Can you explain why?
推荐答案
char * fgets ( char * str, int num, FILE * stream );
从输入流中读取字符,并将它们作为C字符串存储到str中,直到已读取(num-1)个字符或到达换行符或到达文件末尾为止,以先发生的为准.
Reads characters from input stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.
换行符使fgets停止读取,但是该函数将其视为有效字符并包含在复制到str的字符串中.
A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str.
在复制到str的字符之后会自动附加一个终止的空字符('\ 0').
A terminating null character ('\0') is automatically appended after the characters copied to str.
这篇关于fgets在输入末尾添加\ 0或\ n吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!