使用%* C的危害,清除缓冲区scanf函数 [英] Dangers of using %*c to clear the scanf buffer

查看:232
本文介绍了使用%* C的危害,清除缓冲区scanf函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么危险,使用在scanf中的%* C()必要时清除缓冲区。

Are there any dangers to using %*c in scanf() to clear the buffer when necessary.

例如:

char c;
for (int i = 0; i < 5; i++) {
  scanf("%c%*c", &c);
}

或者

char* str;
char c;
int i;
scanf("%s", str);
scanf("%d%*c", &i);
scanf("%c%*c", &c);

如果有是缓冲区溢出或其他安全问题的任何关注?
似乎是这样的C(修改这是不正确的),星号scanf函数的用法没有正式的文件,所以我无法找到确切发生了什么多余的字符被输入。
有没有用C清除scanf函数缓冲的更好的办法?

Should there be any concern for buffer overflows or other security issues? There seems to be no formal documentation for the usage of the asterisk in scanf this way for C (EDIT This is not true), so I'm having trouble finding out exactly what happens to the extra characters that are inputted. Is there a better way of clearing the scanf buffer in C?

推荐答案

您将有更好的运气概念化你想完成的是我怎么读取和丢弃的用户可能已经后输入的任何垃圾任务我在乎,这将导致你的构造,比如

You'll have better luck conceptualizing the task you're trying to accomplish as "how do I read and discard any junk that the user might've typed after what I care about", which will lead you to constructs such as

int c;
while ((c = getchar()) != EOF && c != '\n') ;  /* discard till end of line or EOF */

但同时,你可以摆在首位,这是的 scanf函数避免整个问题=htt​​p://stackoverflow.com/questions / / 9134208 /输入按使用 - 获取功能9134440#9134440>一个好主意,其他几个原因。阅读整线, 函数getline ,如果你有,或 与fgets 如果你不这样做,并用手解析。

But also, you can avoid the entire problem by not using scanf in the first place, which is a good idea for several other reasons. Read entire lines with getline, if you have it, or fgets if you don't, and parse them by hand.

这篇关于使用%* C的危害,清除缓冲区scanf函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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