Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Input String of unknown size?? (http://www.go4expert.com/forums/input-string-unknown-size-t2924/)

tedman 9Feb2007 07:49

Input String of unknown size??
 
Code:

struct emp{
char *name;
int age;
};

struct emp apple;

main(){
printf("Enter your name :");
//what do i put in here?
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??

DaWei 9Feb2007 19:56

Re: Input String of unknown size??
 
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.


All times are GMT +5.5. The time now is 21:35.