Input String of unknown size??

Discussion in 'C' started by tedman, Feb 9, 2007.

  1. tedman

    tedman New Member

    Joined:
    Jan 28, 2007
    Messages:
    10
    Likes Received:
    0
    Trophy Points:
    0
    Code:
    struct emp{
    char *name;
    int age;
    };
    
    struct emp apple;
    
    main(){
    printf("Enter your name :");
    [B]//what do i put in here?[/B]
    printf("Enter you age :");
    scanf("%d", &apple.age);
    
    printf("Your name : %s", apple.name);
    printf("Your age : %d", apple.age);
    }
    
    Please help me with this, or is there any other way to do it??
     
  2. DaWei

    DaWei New Member

    Joined:
    Dec 6, 2006
    Messages:
    835
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Semi-retired EE
    Location:
    Texan now in Central NY
    Home Page:
    http://www.daweidesigns.com
    You can write a lot of code to measure input as you go and allocate/reallocate buffer on the fly. In this instance, that's a rather poor idea. Decide what a sensible maximum length for a name is, and allocate enough to hold it. You MUST be sure to restrict the amount of accepted input to that range, regardless of what the user tries to provide. Users are careless, malicious, fall asleep with their forehead on the keyboard, any number of things. The responsibility for controlling buffer overflow is yours. Failing to do so can lead to crashes or exploits or any number of bad things.

    You should read about scanf, if you're going to use it. You should always check its return value for success; it doesn't promise to succeed, it promises to succeed or TELL YOU IF IT FAILS. That statement is true for most library functions. Not using it is the sign of a novice, at best, and a schlocky programmer, at worst.

    Personally, I would forego scanf and use fgets, which fetches an entire line, OR, at a maximum, the number of characters you have specified as a limit. You can tell whether you got the entire entry, or whether the limit was reached, by the presence or absence of a newline as the last character.

    If you decide to use scanf, you can use a width specifier. Again, read the documentation for your functions. A simple prototype is not enough information to allow you to use them correctly and robustly.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice