gets函数在何种情况下能够使用

本文探讨了gets函数的历史变迁,从C99标准到C14标准中被完全移除的过程,以及在不同C标准版本下使用该函数时遇到的警告与错误。通过示例程序演示了从C98到C17各版本编译器对gets函数的不同反应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于gets函数:

gets函数是一个很有争议的函数,因为它存活了一段时间,然后有被废弃了。

C99官方文档(第297页):

7.19.7.7 The gets function
Synopsis
1 #include <stdio.h>
char *gets(char *s);
Description
2 The gets function reads characters from the input stream pointed to by stdin, into the
array pointed to by s, until end-of-file is encountered or a new-line character is read.
Any new-line character is discarded, and a null character is written immediately after the
last character read into the array.
Returns
3 The gets function returns s if successful. If end-of-file is encountered and no
characters have been read into the array, the contents of the array remain unchanged and a
null pointer is returned. If a read error occurs during the operation, the array contents are
indeterminate and a null pointer is returned.

C11官方文档(前言,第14页):

removed the gets function (<stdio.h>)

C99文档告诉我们,gets函数的返回值是字符串的首地址,然后C11文档告诉我们,gets函数已经被移除了,实际上,在C11中并没有移除gets函数,直到C14才完全移除了gets函数,笔者做了如下实验。

示例程序:

#include <bits/stdc++.h>
using namespace sts;
int main(void){
    char a[10];
    gets(a);
    return 0;
}

然后分别用C98,C11,C14,C17运行了一下,结果如下:

g++ -o test test.cpp -std=c++98抛出waring,gets is dangerous
g++ -o test test.cpp -std=c++11抛出waring,gets is dangerous
g++ -o test test.cpp -std=c++14抛出error,gets is not declared
g++ -o test test.cpp -std=c++17抛出error,gets is not declared

所以,如果我们用了C14以上版本,我们就不要使用gets函数了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值