函数gets的原型为:char*gets(char*buffer);
在 stdio.h中定义,如果要程序中用到此函数需包含#include<stdio.h>
gets()函数用来从标准输入设备(键盘)读取字符串直至接受到换行符或EOF时停止结束,并将读取的结果存放在buffer指针所指向的字符数组中,但换行符会被丢弃,然后在末尾添加'\0'字符。
The line consists of all characters up to and including the first newline character ('\n'). gets then replaces the newline character with a null character ('\0') before returning the line. In contrast, the fgets function retains the newline character. _getws is a wide-character version of gets; its argument and return value are wide-character strings.
-----from msdn
调用格式为:gets(s); 其中s为字符串变量(字符串数组名或字符串指针)。
返回值:读入成功,返回与参数buffer相同的指针;读入过程中遇到EOF(End-of-File)或发生错误,返回NULL指针。所以在遇到返回值为NULL的情况,要用ferror或feof函数检查是发生错误还是遇到EOF。
gets(s)函数与 scanf("%s",s) 相似,但不完全相同,使用scanf("%s",s) 函数输入字符串时存在一个问题,就是如果输入了空格会认为字符串结束,空格后的字符将作为下一个输入项处理,但gets()函数将接收输入的整个字符串直到遇到换行为止。
注意:本函数可以无限读取,不会判断上限,所以程序员应该确保buffer的空间足够大,以便在执行读操作时不发生溢出。为了避免这种情况,我们可以用fgets()来替换gets()。
宽字符版本,当使用unicode宽字符文本时,使用这个函数 _getws();
【百科查阅】
注意编译的时候这段警告信息:
warning C4996: 'gets': This function or variable may be unsafe. Consider using gets_s instead. To disable deprecation,use _CRT_SECURE_NO_WARNINGS. See online help for details.
贴子中的一段代码,也粘到这里看下了
#include <stdio.h>
int main ()
{
char string[100];
int i,num=0,word=0;
char c;
gets(string);
for (i=0;(c=string[i])!='\0';i++) //这里为什么不能使'\n'了???
{
if (c==' ')
word=0;
else if(word==0)
{
word=1;
num++;
}
}
printf ("there are %d words in this line .\n",num);
return 0;
}
上述理论中msdn中的一段正好说明了这个知识点:
The line consists of all characters up to and including the first newline character ('\n'). gets then replaces the newline character with a null character ('\0') before returning the line.
--------------------------------------------------------------
#include <stdio.h>
int main(void)
{
char buffer[21]; //20 chars + '\0'
gets(buffer);
//danger :there is no way to limit the number of characters
printf("You input was %s\n",buffer);
system("pause");
return 0;
}
这段代码中无法保证缓冲区是否足够大会引起溢出而出错。
----------------------------------------------------------
下面这段测试代码当输入空串按回车()不能正常的结束循环。
#include <stdio.h>
int main(void)
{
char buffer[256];
while(gets(buffer)!=NULL)
{
puts(buffer);
}
return 0;
}
原因在于while(gets(buffer)!=NULL),要使结束循环,需要gets调用失败。
gets返回值是一个指针,也就是输入字符串的地址,而NULL不等于空字符串,也不等于空字符串的地址。
换成下面这条语句:
while(strcmp(gets(buffer),"")!=0)
或者使用下面这段代码
char buffer[256];
gets(buffer);
while(strlen(buffer)!=0)
{
puts(buffer);
gets(buffer);
}