得到()以输入没有实际给它任何输入? [英] gets() taking input without actually giving it any input?

查看:114
本文介绍了得到()以输入没有实际给它任何输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是相当新的C很抱歉,如果这是一个愚蠢的问题,但是当我运行下面的code:

I'm fairly new to C so sorry if this is a stupid question but when I run the following code:

#include <stdio.h>

int main () {
    int i;
    int test[10];
    char string[81];

    for(i = 0; i < 10; i++){
        scanf("%d", &test[i]);
    }

    for(i=0; i < 7; i++){
        gets(string);
        printf("String was entered\n");
    }

}

和进入任何10位数字,被输入的字符串行会被打印,即使我没有进入在命令窗口中的字符串。任何人都可以解释为什么?有没有办法阻止它的发生?

And enter any 10 digits, the line "string was entered" will be printed even though I didn't enter a string in the command window. Can anyone explain why? Is there any way to stop it happening?

谢谢!

推荐答案

在您使用 scanf函数在数据读取,换行依旧坐在输入队列中等待读。 获得读取新行并停止(因为它达到了行的末尾!)

After you read in data using scanf, the newline is still sitting in the input queue waiting to be read. gets reads that newline and stops (because it's reached the end of the line!)

请注意,它的的是一个坏主意的使用获得:它提供了没办法把多少个字符获取读入缓冲区的限制因此,如果你输入的字符数大于将适合在缓冲区中,你最终会溢出缓冲区,从而导致数据损坏,应用程序崩溃,一个巨大的安全漏洞,和/或任意数量的其他未predictable的结果。对于一个安全的选择,你可以使用与fgets 不是与标准输入

Note that it's a bad idea to use gets: it provides no way to put a limit on how many characters get read into the buffer, so if you type in more characters than will fit in the buffer, you'll end up overflowing the buffer, resulting in data corruption, an application crash, a huge security vulnerability, and/or any number of other unpredictable results. For a safe alternative, you can use fgets instead with stdin:

fgets(string, sizeof(string), stdin);

(请注意,你可能想使用某种符号常量为字符串的大小,这样你就不会在多个地方重复它 - 或者使用的sizeof(字符串)当数组定义是可见的。)

(Note that you'd probably want to use a symbolic constant of some kind for the size of string so that you don't repeat it in multiple places - or use sizeof(string) when the array definition is visible.)

这篇关于得到()以输入没有实际给它任何输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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