Re: [vox] Why C?
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [vox] Why C?
On Sat, 2002-02-23 at 23:12, Matthew Johnson wrote:
> On Sat, 2002-02-23 at 22:06, Ryan wrote:
> > -----BEGIN PGP SIGNED MESSAGE-----
> > Hash: SHA1
> > I'm currently teaching myself perl, IT ROCKS!
> Hehe, bet it does :).
> Anyway, took me 15 minutes to remember some simple stuff...But have not
> touched C programming in 3 or so years, even then wasn't that advanced:
> Guess I can share...
> /* Just trying to remember the basics, wish I knew a whole lot more and
> in depth. The source code gives the answers hahaha */
> int me;
> int you;
> int take;
> /* int i; just for later perhaps */
I dislike using globals when they aren't necessary - as a general rule,
you should stick to locals whenever possible. All of the above vars
could just as easily been declared in main().
> int main()
> printf("Simple number game!!!\n");
> printf("Type in a number:");
You should add an extra space after the colon above; and a call to
fflush(stdout) should be placed here, to guarantee that the user can see
the message "Type in..." before he/she is expected to enter something.
> scanf("%d", &me);
Use of scanf() can be a little tricky. In particular, if someone were
to enter "the number 6", scanf() will return 0 and leave that input in
the buffer, causing all the other calls to scanf() to return without
prompting the user, since it will encounter the input which is still in
the buffer and return 0 since it can't parse a number.
It's a little better to write your own utility function for grabbing
integers from the user - something that checks to ensure that valid data
was obtained, and which flushes the rest of the buffer (*not* by
fflush() - that's a typical error which invokes undefined behavior - you
flush stdin by reading characters until you've read a newline).
> printf("the number is %d\n", me);
> printf("Now lets take that number and take it away...Enter number: ");
> scanf("%d", &you);
> printf("Here is the result: %d\n", take);
> printf("Now I am going to try something a little harder.\n");
> if (take!=200)
> printf("Oooops wrong...Choose again, must be between 100 and 200\n");
> printf("That is quite correct, the number was 200...:)\n");
If those are tabs above, you should set your text editor to translate
the tab key into spaces automatically.
> return 0;
> Actually find C++ easier, is that normal? :).
Absolutely. I/O streams were written to be easier in C++, if somewhat
less powerful for certain applications. Many things are easier in C++
than in C, but sometimes the constructs which make some things easier
also force me to make less than ideal choices for other things.
I/O streams have the same problem with leaving malformed input in the
buffer, though, so I'd probably use the string library's getline()
function in combination with either ostringstreams or C's strtol()
facility (the latter being more efficient).
vox mailing list