Input by using gets function

后端 未结 3 2080
有刺的猬
有刺的猬 2020-12-06 23:08

In Below Code When I want to Enter Record of second student or >2 student .. Compiler skip Name Input and take Input for class and age .. What a problem please help me ?

相关标签:
3条回答
  • 2020-12-07 00:07

    First off, never use gets. There is no way to tell it how big your buffer is, so it will cheerfully write input past the end and make the program blow up. This used to be the number one cause of remotely exploitable security holes in network servers.

    Second off, never use any of the *scanf functions either, because:

    1. Some scanf format strings are just as unsafe as gets, notably %s with no size modifiers.
    2. Numeric overflow inside scanf provokes undefined behavior, which means your program may crash simply because someone typed a number that was too big.
    3. It is extremely difficult to write a robust input parser using scanf, because if it fails, it does not tell you precisely where the problem characters were.

    For a simple task like this one, you should use fgets (or, better, getline if you have it) and convert the age to an integer with strtoul. (Age cannot be negative, so you want the unsigned version. Don't use atoi and friends - just like *scanf, they don't give you enough information about invalid input.)

    For more complicated tasks, you should reach for lex and yacc.

    0 讨论(0)
  • 2020-12-07 00:09

    The problem is common enough. Try this:

    scanf("%d ", &a[i].age);
             ^ <--- This space will make scanf eat the remaining blanks
    

    There are C FAQs about this:

    • Scanf interlace
    • Scanf problems
    • Flushing stdin

    Secondary notes:

    • Don't use gets. Use fgets instead.
    0 讨论(0)
  • 2020-12-07 00:14

    It's the scanf. When you press ENTER after it, the newline completes the next call to gets.

    To fix this, you can add a getchar at the end of the loop, after the scanf, which will consume the newline.

    for(int i=0 ; i<5 ; i++)
    {
        printf("\n Enter Name  :");
        gets(a[i].Name);
        printf("\n Enter Class :");
        gets(a[i].Class);
        printf("\n Enter Age   : ");
        scanf("%d" , & a[i].age);
        getchar();
    }
    
    0 讨论(0)
提交回复
热议问题