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