[TriLUG] a C question
Paul D. Boyle
boyle at laue.chem.ncsu.edu
Wed Oct 23 10:06:21 EDT 2002
Greg 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;
This doesn't need to be global. Put this in the body of main().
>
> int main(void)
> {
>
> printf("What is your favorite number?\n");
> scanf("%d", &fav_num);
It is always a good idea to see what scanf() returns. If you do this
with your code you will see that the scanf() function scanned 0 items
when you enter text. This means input was available but the conversion
wasn't done.
> 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?
If you want to read in character data use a character array or a pointer to
char which points to dynamically allocated memory.
The comp.lang.c newsgroup is a good place to ask C questions (but do read the
FAQ for the group first, it is quite informative).
If you want read text you use a combination of fgets() and sscanf()
(note the 'ss'). The comp.lang.c FAQ explains how to use these functions.
Good Luck,
Paul
--
Paul D. Boyle | boyle at laue.chem.ncsu.edu
Director, X-ray Structural Facility | phone: (919) 515-7362
Department of Chemistry - Box 8204 | FAX: (919) 515-5079
North Carolina State University | http://www.xray.ncsu.edu
Raleigh, NC, 27695-8204
More information about the TriLUG
mailing list