[TriLUG] a C question

Tanner Lovelace lovelace at wayfarer.org
Wed Oct 23 10:12:52 EDT 2002


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.

fav_num is declared as an integer.  You then specify to scanf a %d,
which stands for a "decimal" number.  Therefore, scanf is looking
for a decimal number which it converts from the string you entered
to the end format.  When you enter a string, it tries to convert
and gets an error.  Since it was looking for a number and didn't
find one, it just returns 0 which scanf then assigns to fav_num.

Tanner
-- 
Tanner Lovelace | lovelace at wayfarer.org | http://wtl.wayfarer.org/
--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--
GPG Fingerprint = A66C 8660 924F 5F8C 71DA  BDD0 CE09 4F8E DE76 39D4
GPG Key can be found at http://wtl.wayfarer.org/lovelace.gpg.asc
--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--
          Si hoc legere scis, nimium eruditionis habes.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part
URL: <http://www.trilug.org/pipermail/trilug/attachments/20021023/b70659d6/attachment.pgp>


More information about the TriLUG mailing list