Coder's Guild Mailing List

RE:Using getchar() instead of fgets or scanf

Posted by Mathieu Paquet on 1999-09-28

I think this code should work (it worked with Borland C++ 3.1 compiler).
Your For() loop wasn't correct and you didn't used the correct char
ype( char c  should be char c[20] to put a string)... as you will notice,
the "c[i]=0;" in my code tells to the compiler that the string end when you
press "Enter".

**************************
#include <stdio.h>
#include "conio.h"

void main()
{
 char c[20];
 int i=0;

 clrscr();

 printf("please enter the name\n");

 for(;;)
   {
    c[i]=getchar();

    if(c[i]=='\n')
      {
      c[i]=0;
      break;
      }

   i+=1;

   }

 printf("\nyour name is %s and has %d characters",c,i);

 getch();

}

> >
> 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
>