得到()函数用C [英] gets() function in C

查看:95
本文介绍了得到()函数用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要再次求助!我认为这是pretty酷使用获得()函数,因为它就像 scanf()的其中,我能得到与空白输入。但是,我在一个线程(学生信息文件处理),这是不好的阅读使用,因为据他们说,它是一个魔鬼的创建缓冲区溢出(我不明白)

工具

如果我使用获得()功能,我可以做到这一点。输入您的姓名:基努·里维斯

如果我使用 scanf()的,我只能这样做。填写您的姓名:基努

于是我听从他们的建议,并取代了我所有的获得() code。与与fgets()。现在的问题是我的一些codeS都没有工作了...有没有比之外的任何功能得到()与fgets() 它可以读取整条生产线和忽略空格。


解决方案

  

这是一个魔鬼的工具,用于创建缓冲区溢出


由于 获得 不取长度参数,它不知道你的输入缓冲区有多大。如果在10个字符的缓冲区传递和用户输入100个字符 - 好,你明白了吧

与fgets 是一个更安全替代获得,因为它需要的缓冲区长度作为参数,所以你可以这样调用它:

 与fgets(STR,10,标准输入);

和它至多9个字符读取


  

现在的问题是我的一些codeS都没有工作了。


这是可能是因为与fgets 还存储了最后的换行符( \\ n )字符在你的缓冲区 - 如果您code未期待这一点,你需要手动删除它:

  INT LEN = strlen的(STR);
如果(LEN大于0和放大器;&安培; STR [LEN-1] =='\\ n')
  STR [LEN-1] ='\\ 0';

I need help again! I thought it is pretty cool to use the gets() function because it is like the scanf() wherein I could get an input with whitespace. But I read in one of the threads (student info file handling) that it is not good to use because according to them, it is a devil's tool for creating buffer overflows (which I don't understand)

If I use the gets() function, I could do this. ENTER YOUR NAME: Keanu Reeves.

If I use the scanf(), I could only do this. ENTER YOUR NAME: Keanu

So I heed their advice and replaced all my gets() code with fgets(). The problem is now some of my codes are not working anymore...are there any functions other than gets() and fgets() which could read the whole line and which ignores the whitespace.

解决方案

it is a devil's tool for creating buffer overflows

Because gets does not take a length parameter, it doesn't know how large your input buffer is. If you pass in a 10-character buffer and the user enters 100 characters -- well, you get the point.

fgets is a safer alternative to gets because it takes the buffer length as a parameter, so you can call it like this:

fgets(str, 10, stdin);

and it will read in at most 9 characters.

the problem is now some of my codes are not working anymore

This is possibly because fgets also stores the final newline (\n) character in your buffer -- if your code is not expecting this, you should remove it manually:

int len = strlen(str);
if (len > 0 && str[len-1] == '\n')
  str[len-1] = '\0';

这篇关于得到()函数用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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