layout: post
title: “gets fgets scanf 的区别”
date: 2019-10-7
categories: linux
tags: C C++ linux
gets
-
函数:char *gets(char *str)
-
功能:从标准输入获取string。
-
参数:str ,指向用来存取C string的buffer的指针。
-
返回值:成功,返回str字符串;失败,返回NULL指针。
注:gets不接收’\n’,并在字符串末尾自动追加’\0’,缓存区’\n’会被清除。
输入字符串长度超过buffer,会有溢出错误。
在linux中使用gets会出现安全警告“warning:the ‘gets’ function is dangerous and should not be used.”,可以用fgets。
fgets
-
函数:char *fgets(char *str, int num, FILE *stream)
-
功能:从stream中读取字符,并作为C string存入到str中。
-
参数:
str: 指向用来存放string的char数组的指针
num:被读取的最大字符数目(包括’\0’字符),通常用str数组的长度
stream:指针,指向一个FILE对象,fgets从这个对象中读取字符。
-
返回值:成功,返回str字符串;失败,返回NULL指针。
注:fgets接收’\n’,并在字符串末尾自动追加’\0′
第三个参数输入stdin,可用于读取标准输入
scanf
-
函数:int scanf(const char *format, …)
-
功能:从标准输入读取数据,动态为某些变量赋值。
-
参数:根据需要赋值的变量类型决定。
-
返回值:成功:正整数;失败:-1。
为某些变量赋值。
-
参数:根据需要赋值的变量类型决定。
-
返回值:成功:正整数;失败:-1。
注:scanf遇到空格、回车和Tab键都会认为输入结束