[C / C ++ syntax] -gets function and function fgets

gets function

gets Function Description

gets function prototype is

char* gets(char* buffer);

until the read function gets a string ** '\ n' ** end, and the final read '\ n' into '\ 0' (end of the string flag)
first gets function returns the address of an array, from It began to spread into the first address array of characters
if the read fails will return NULL

gets function defect

gets function will not determine the upper limit, that gets function may lead to an array of characters to read too much overflow, it should be noted that the array size in the program, to prevent overflow might otherwise modify the data stack!

fgets function

fgets Function Description

gets function prototype is

char* fgets(char* buffer, int bufsize, FILE *stream)

Finally, it requires a third parameter to indicate which file to read. If the data is read from the keyboard, it can be used as the parameter stdin, as shown in the following code:

#include <stdio.h>
int main(void)
{
	char a[105];
	fgets(a, 11, stdin);
	puts(a);
	return 0;
}

Input: aaaaaaaaaaa
Output: aaaaaaaaaa

First, gets function is different, not read newline function fgets, and will read the last character replaces '\ 0', means that the last character will not be able to store data, bufsize is the number of the character string you want to enter, for example, when you want to enter n characters, bufsize should be set to n + 1, which is 10 above a reason code output.
Note stop reading when fgets function will encounter '\ n' or n-1 has been read characters:
summary : When you want to enter a string of n characters has just set the second parameter to n + 1 can, fgets function will read the last '\ n' is replaced with '\ 0'

Published 20 original articles · won praise 2 · Views 948

Guess you like

Origin blog.csdn.net/zhbbbbbb/article/details/103412724