Coder's Guild Mailing List

Re: Using getchar() instead of fgets or scanf

Posted by G.P.Gillis on 1999-09-29

The problem was you kept reassigning the value of c each time the getchar() function was called.  When the for loop exits, the value of c == \n.  You need to copy each character retrieved by getchar into a string buffer.  I do not know if this is more efficient than fgets or scanf ( of cin.getline in C++ ).  The following is you code with the changes to make it work.

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

	 printf("please enter the name");
	 for (c=getchar();c!='\n';c=getchar()) {
	     str[i] = c;
		 i+=1;
		 
	 }
	 printf("your name is %s and has %d characters",str,i);
}


GPG

G.P.Gillis - Programmer / Technician
gpgillis@xxxx.xxx

Teach Your Children Well ...