Coder's Guild Mailing List

Re:Using getchar() instead of fgets or scanf

Posted by Guadalupe E Ruiz/MATA2/MFG/KEMET/US on 1999-09-28

Hello, maybe this can help you!!!

First you have to declare your variable as a char array (*c), then you have
to
give it some memory, so you have to use calloc to allocate memory,  your
program can look like this:

#include <stdio.h>
#include <malloc.h>
void main()
{
   char *c;   /* char array */
   int i=0;

   c = calloc( 20, sizeof( long ) );   /* allocate memory 20 chars */
   printf("please enter the name ");
   for (c[i]=getchar();c[i]!='\n';c[i]=getchar())  /* you use c[i] to tell the memory location of every*/
   {                                               /* char */
    i+=1;
   }
   printf("your name is %s and has %d characters",c,i);  /* %s puts all the string */
   free( c ); /*Free memory used by c */                 /* you can use %c,c[i] to */
                                                    /* print only one char i=0,1..*/
}



P.D.
 Sorry, my writing in english is not very good, I hope you understand it
and help
 you ...

>Date: Tue, 28 Sep 1999 21:22:25 +0800
>From: "Hasan" <kacmaz@xxxxx.xxxxx.xxx.xx>
>Subject: Using getchar() instead of fgets or scanf
>
>It has been told always that usage of fgets or scanf is not an efficient
way
>to read keyboard input streams. I thought about using the following code
but
>even though it complies ok, it does not run? can anyone help? or anyother
>suggestions instead of this code...?
>
>thx
>
>
>#include <stdio.h>
>void main()
>{
> char c;
>   int i=0;
>
>   printf("please enter the name");
>   for (c=getchar();c!='\n';c=getchar())
>   {
>    i+=1;
>   }
>   printf("your name is %s and has %d characters",c,i);
>}