Darin McBride suddenly realized that he had nothing to do with
Simon Law or "atoi(const char *s)."
Hi Darin McBride,
SL> Be warned... I am a "newbie" to C. (Please don't hurt me
SL> too much...)
DM> Cool... a user from my own BBS... I'll only hurt you locally. ;->
As opposed to globally huh? *chuckle*
SL> char *sTemp;
SL> int iTemp;
SL> printf("Enter a number: ");
SL> scanf("%s", sTemp);
DM> Ooo.... so far, so bad. sTemp doesn't point anywhere. You need to
DM> give it some memory.
I suppose that was a big no-no, huh? All those dang C
tutorials are USELESS I tell you USELESS.
BTW, why DOES it have to point to a memory location? And
why do you have to define a specific maximum length to the string?
DM> #define TEMP_LEN 30
DM> char* sTemp = malloc(TEMP_LEN) * sizeof(char)); /* remember to free it
DM> afterwards */
Okay. This means to allocate 30 chars with of 1 byte each,
right? And I use free(sTemp) afterwards!
(BTW, is there a difference between "char* sTemp" and
"char *sTemp"?)
DM> Next problem: scanf. If the user types in more characters than the
DM> array has room for, you'll overwrite it. You could do the following:
DM> scanf("%" STR(TEMP_LEN) "s", sTemp);
DM> Where STR is:
DM> #define _STR(x) #x
DM> #define STR(x) _STR(x)
DM> (A pair of defines are available in Snippets which are close to this
DM> [perhaps a name change] - I should have Snippets available for
DM> download, if not, bug me in private mail and I'll find it for ya.)
DM> Anyway, this is getting ugly. However, there is a reason to this
DM> madness, and it is a point on how to get really ugly code that works.
DM> ;-)
All right, you've gone and lost me here. Please explain
those two previous #defines...
DM> Let's try two different solutions at this point.
DM> 1. Use scanf.
Okay. I understood that.
DM> 2. Parse everything manually
Got this one too...
DM> What a lot of work to do error-correction (error-protection?)!
DM> Thus
DM> the reason for so many generic user-entry modules... so we don't have
DM> to continually do all of this... :-)
Generic user-entry modules? You mean extra... dang, I
don't know the C terminology...
SL> Is there a way of doing this using a standard function, or
SL> do I have to check for a zero (\0x30?) in sTemp if atoi returns a 0?
DM> You could do this - the only reason for the longer solutions above is
DM> to help you should you want more than just a single number... :-)
Thank you very much, then!
Scry you later!
Fendolin...
... It's all fun and games till someone looses an eye, then it's a SPORT.
---
---------------
* Origin: Tanktalus' Tower BBS (1:250/102)
|