[TriLUG] a C question

Jeremy Portzer jeremyp at pobox.com
Wed Oct 23 10:10:27 EDT 2002


Greg,

C is a strongly typed language, meaning that since you since you
declared fav_num as an integer, it can only hold an integer, regardless
of what you try to put in it.  And yes, the %d format specification in
scanf means "integer" too.  So there's no possible way text (called a
"string" in programming terminology) would work.  And a string in C is
not a simple beast; you'll learn about strings later in your book I'm
sure.  

(Note that improper handling and understanding of strings is one of the
big reasons for the "buffer overflow" security exploits that we're
always hearing about.)

You may want to join the dev at trilug.org list and post your C questions
there; it's aimed more at this type of discussion.

Also, your variable declaration, "int fav_num;" should really be inside
your main() function, not hanging out by itself.

Hope this helps,
Jeremy
(not really a programmer, so hopefully everything I said is correct!)

On Wed, 2002-10-23 at 09:45, Greg Brown wrote:
> I'm teaching myself C and I'm confused about something (and I'm only on day 3 
> of "teach yourself in 21 days" so I'm still doing really basic things).
> 
> The following program complies and does what I expect it to (return a number 
> to STDOUT):
> 
> #include<stdio.h>
> 
> int fav_num;
> 
> int main(void)
> {
> 
> 	printf("What is your favorite number?\n");
> 	scanf("%d", &fav_num);
> 	printf("\n\nYour favorite number is %d\n\n", fav_num);
> 	return 0;
> }
> 
> If I try to enter text instead of a number the program returns 0, not the 
> text.  The issue seems to be %d gizmo which I'm guessing can only be a 
> numeric, not text.  Or is the problem the way I've declared the variable 
> fav_num?  Is there a different way to declare a variable when it is text?  Or 
> is the issue %d?
> 
> Just curious.
> 
> And thanks!
> 
> Greg
> 
> 
> _______________________________________________
> TriLUG mailing list
>     http://www.trilug.org/mailman/listinfo/trilug
> TriLUG Organizational FAQ:
>     http://www.trilug.org/~lovelace/faq/TriLUG-faq.html
> 





More information about the TriLUG mailing list