【问题标题】:C programming--why gets() not taking input? [duplicate]C 编程——为什么 gets() 不接受输入? [复制]
【发布时间】:2017-04-02 17:13:13
【问题描述】:
#include<stdio.h>
int main()
{
   int choice;
   char sl[10];
   char phn[10];
   printf("Enter choice: ");
   scanf("%d",&choice);
   switch(choice)
   {
   case 1:
       printf("\nEnter Student Details: \n\n");
       printf("\nEnter serial number: ");
       gets(sl);
       printf("Roll number: ");
       gets(phn);
   default:
      break;
   }
   return 0;
}

C 编程:

我在这里使用了 2 个 gets() 函数。第二个正在工作,但第一个不工作。为什么??如何让它发挥作用?

注意:我想将“sl”和“phn”变量作为 char 类型,并且我想使用 gets() 来获取输入。 请有人帮忙....

【问题讨论】:

  • 想一想:为scanf 输入的数字,您使用什么键来结束输入?提示:Enter 键也将作为换行符放入输入缓冲区。
  • gets 很危险且已弃用(并已从 C11 标准中删除)。使用fgets 或者getline

标签: c scanf


【解决方案1】:

对所有输入使用 fgets。 scanf 通常会在输入流中留下一个换行符,这会导致 fgets 出现问题。使用 sscanf 解析输入的整数并检查返回以确保输入了整数。

#include  <stdio.h>
int main()
{
    int choice;
    int result = 0;
    char sl[10];
    char phn[10];
    char input[256];
    do {
        printf("Enter choice: ");
        if ( ( fgets ( input, sizeof input, stdin))) {
            result = sscanf( input, "%d", &choice);
            if ( result == 0) {
                printf ( "try again\n");
            }
        }
        else {
            fprintf ( stderr, "problem getting input\n");
            return 1;
        }
    } while ( result != 1);
    switch(choice)
    {
        case 1:
            printf("\nEnter Student Details: \n\n");
            printf("\nEnter serial number: ");
            if ( ( fgets ( sl, sizeof sl, stdin)) == NULL) {
                fprintf ( stderr, "problem getting serial number\n");
                return 1;
            }
            printf("Roll number: ");
            if ( ( fgets ( phn, sizeof phn, stdin)) == NULL) {
                fprintf ( stderr, "problem getting roll number\n");
                return 1;
            }
            break;
        default:
            break;
    }
    return 0;
}

【讨论】:

    【解决方案2】:

    永远不要使用gets()。它没有针对缓冲区溢出漏洞提供任何保护(也就是说,您无法告诉它传递给它的缓冲区有多大,因此它无法阻止用户输入大于缓冲区的行并破坏内存)。

    fgets() 是安全的,因为您可以通过传入缓冲区大小(包括 NULL 的空间)来保证永远不会溢出输入字符串缓冲区。

    最重要的区别是fgets()知道字符串有多大 是,gets() 不是。这意味着几乎不可能写 使用gets() 的安全代码,所以不要这样做。

    在那里使用fgets() 而不是gets()

    【讨论】:

      猜你喜欢
      • 2021-12-06
      • 1970-01-01
      • 2020-05-13
      • 2015-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多