soda
soda

Reputation: 523

Its a student diary program in c.when i try to input name of student by gets compiler skips name it works with scanf but it cant input spaces

void signup(struct user *u)

 { char c_pswd[80];
   int i,flag=1;

   clrscr();

   printf("\n>ENTER FULL NAME: ");
   gets(u->name);//scanf("%s",u->name);

   printf("\n>ENTER USERNAME: ");
   scanf(" %s",u->username);

   printf("\n>ENTER DATE OF BIRTH: ");
   scanf(" %s",u->dob);

   printf("\n>ENTER EMAIL: ");
   scanf(" %s",u->email);

   printf("\n>ENTER GENDER(M/F): ");
   scanf(" %c",&(u->gender));

   printf("\n>ENTER MOBILE NUMBER: ");
   scanf("%d",&u->mobile_no);

   while(flag==1) {

   printf("\n>ENTER PASSWORD(ATLEAST 8 CHAR): ");
   scanf("%s",u->password);

   printf("\n>CONFIRM PASSWORD: ");
   scanf("%s",c_pswd);

   if(strcmp(u->password,c_pswd)!=0)

    {
       clrscr();

       printf("\t\tPASSWORDS DON'T MATCH ENTER AGAIN...");

      }

   else {

     clrscr();
     printf("\n\n\n\n\n\n\n\t\t\tSIGNUP SUCCESFUL!!!");

     printf("\n\n\nREDIRECTING TO LOGIN...");

     delay(5000);//time delay of 5 seconds
     flag=0;//AGAIN GOES FOR PASSWORD INPUT AND VERIFICATION

    }
  }
}

Upvotes: 0

Views: 44

Answers (1)

Clifford
Clifford

Reputation: 93524

It is not clear perhaps from the information given why gets() fails while the commented-out scanf() call works, however console input is generally line buffered, and if a say some preceding input processing has not consumed the buffered data and the buffer contains a , that buffered line will be accepted as the input without waiting for further input.

For for example if you had:

menu_select = getchar() ;
if( menu_select == 's' )
{
    signup( &user ) ;
}

The user may enter s<newline> but the scanf() consumes only the s leaving (\n) in the buffer, so that in signup(), the first input call is immediately satisfied as an empty line.

One pattern for dealing with this is to ensure that all input extracts the whole line. In the above case for example:

menu_select = getchar() ;
while( menu_select != `\n` || getchar() != `\n ) ; // empty flush loop
if( menu_select == 's' )
{
    signup( &user ) ;
}

Consider encapsulating it:

char inchar()
{
    char ch ;
    scanf( "%c", &ch) ;
    while( ch != `\n` || getchar() != `\n ) ; // empty flush loop
    return ch ;
}

The problem occurs with any input that does not process the entire line, not just getchar(), but also scanf() and gets() which is it is not clear if or how your scanf() version works.

Upvotes: 2

Related Questions