在C中的gets()函数字符串函数认为是不好的做法? [英] Is the gets() string function in C considered a bad practice?

查看:126
本文介绍了在C中的gets()函数字符串函数认为是不好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在读头第一个C的书和整个笔者偶然说获得()是一个不好的做法

was reading the Head first C book and stumbled across the author saying gets() to be a bad practice

获得()是一个函数,是
              存在了很长一段时间。
              但是,你真的需要知道
              是,你真的不应该
              使用它。

gets() is a function that’s been around for a long time. But all you really need to know is that you really shouldn’t use it.

为什么它被认为是不好的做法?

why is it considered a bad practice?

推荐答案

考虑

#include<stdio.h>
int main()
{
    char buffer[100];
    gets(buffer);
    printf("The input is %s",buffer);
}

当于99长度的用户输入类型则没有问题。但是,当用户键入超过99个字符它试图写入到内存中不属于它。

When user types input of length within 99 then there is no problem. But when user types more than 99 characters it tries to write into memory it doesn't own.

最糟糕的是它会导致异常行为和程序终止,而不留下用户感到困惑关于当前形势的任何信息。

The worst thing is it causes abnormal behaviour and the program terminates without any information which leaves user baffled about the current situation

另一种方法是使用字符*与fgets(字符* S,INT大小,文件*流); 函数

更新:如指出由@pmg:得到()删除换行,而与fgets()保留新行

Update: As pointed by @pmg : gets() removes newline while fgets() retains the new line

这篇关于在C中的gets()函数字符串函数认为是不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆