[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Bill Cunningham

4/24/2011 12:47:00 AM

I have been away from C for awhile and need a refresher. fgets 2nd
parameter takes an int but the 1st takes a string. When I compile what I
write everything works fine but this is what I type-

#include <stdio.h>

int main()
{
char p[5];
printf("enter code-> ");
fflush(stdout);
fgets (p,sizeof(int),stdin);
printf("%s\n",p);
return 0;
}

Everything's cool and works the way I want. But is there a similarity
with the 5 chars and the ints in fgets 2nd parameter? I shouldn've used 5
for int should I have?

Bill


2 Answers

China Blue Veins

4/24/2011 1:49:00 AM

0

In article <4db372f6$0$10419$bbae4d71@news.suddenlink.net>,
"Bill Cunningham" <nospam@nspam.invalid> wrote:

> I have been away from C for awhile and need a refresher. fgets 2nd
> parameter takes an int but the 1st takes a string. When I compile what I
> write everything works fine but this is what I type-
>
> #include <stdio.h>
>
> int main()
> {
> char p[5];
> printf("enter code-> ");
> fflush(stdout);
> fgets (p,sizeof(int),stdin);
> printf("%s\n",p);
> return 0;
> }
>
> Everything's cool and works the way I want. But is there a similarity
> with the 5 chars and the ints in fgets 2nd parameter? I shouldn've used 5
> for int should I have?

Any relation would be accidental. I use code like
char p[N]; fgets(p, sizeof p, stdin);
so I specify the buffer size once and I let the compiler take care of all other
references.

If you think about, the maximum number of characters of an int is
1+1+log10(INT_MAX). (The extra 1+ for a sign character.)

--
Damn the living - It's a lovely life. I'm whoever you want me to be.
Silver silverware - Where is the love? At least I can stay in character.
Oval swimming pool - Where is the love? Annoying Usenet one post at a time.
Damn the living - It's a lovely life. Why does Harmony have blue veins?

Gregory Pietsch

5/4/2011 11:48:00 PM

0

On Apr 23, 8:46 pm, "Bill Cunningham" <nos...@nspam.invalid> wrote:
>     I have been away from C for awhile and need a refresher. fgets 2nd
> parameter takes an int but the 1st takes a string. When I compile what I
> write everything works fine but this is what I type-
>
> #include <stdio.h>
>
> int main()
> {
>     char p[5];
>     printf("enter code-> ");
>     fflush(stdout);
>     fgets (p,sizeof(int),stdin);

What's the sizeof(int) for? The fgets function reads in a string. If
you want to convert the string to an integer, use atoi, atol, atoll,
strtol, strtoul, or strtoull. -- Gregory Pietsch

>     printf("%s\n",p);
>     return 0;
>
> }
>
>     Everything's cool and works the way I want. But is there a similarity
> with the 5 chars and the ints in fgets 2nd parameter? I shouldn've used 5
> for int should I have?
>
> Bill