Input String of unknown size??

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

  1. tedman

    tedman New Member

    Jan 28, 2007
    Likes Received:
    Trophy Points:
    struct emp{
    char *name;
    int age;
    struct emp apple;
    printf("Enter your name :");
    [B]//what do i put in here?[/B]
    printf("Enter you age :");
    scanf("%d", &apple.age);
    printf("Your name : %s",;
    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

    Dec 6, 2006
    Likes Received:
    Trophy Points:
    Semi-retired EE
    Texan now in Central NY
    Home Page:
    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