gets() and fgets() Not Working Properly - Source Included 
Author Message
 gets() and fgets() Not Working Properly - Source Included

Quote:

> I've tried gets() and almost everyone suggested I use fgets().
> I did but I still get the same result.  Specifically, when I
> select (1) to Add Customer,
> In other words, it skips over the first step to enter the
> Customer ID number.

> Why?

> Many thanks in advance.

> Raymond

[ snipped lot's of code ]
Quote:
> ***

>      puts("7  Print List\n");
>      puts("8  Exit Program\n");
>      printf("Please enter selections: ");
>      select = getchar();

The nice thing about getchar() is that the return-char remains in the
buffer.
Suggestion. Use fgets here as well.

Quote:
>      putchar('\n');
>      switch(select)
>      {
> int addcust(void)
> {

[ snipped more code ]
Quote:
>      printf("Enter the Zipcode: ");
>      fscanf(stdin,"%d", &info.Zipcode);

SCANF-alert: This buffers another newline character (and maybe some
other stuff as well. Use fgets and the sscanf to obtain the integer.

Quote:
>      getslot();
>      fwrite(&info, sizeof(info), 1, fp);
>      fclose(fp);
>      getslots();
> return 1;
> }

> int delcust(void)
> {    /*****
[snipped more code]
>      puts("Delete Customer Function\n");
>      printf("Please enter the name of the Customer: ");
>      gets(delname);

GETS-alert: use fgets().

[ SNIPPED A LOT OF CODE]

There's always a big thing against using scanf() and gets().
gets() is dangerous because it allows the user who's giving
input to enter more data than first in the buffer, use
fgets() instead. This allows you to put a limit on the
number of bytes you read.

scanf() is even more dangerous. The problem is that input is
buffered in such a way that it's hard to predict how much
you've actually read. For user-input I recommend that you
use fgets() to read the user-input in a temporary buffer.
This reads everything up to the newline, leaving nothing
else in the buffer. Then use sscanf to scan the buffer
for input.

See also the FAQ:
12.20 Why does everyone say not to use scanf? What should I use instead?
http://www.*-*-*.com/ ~scs/C-faq/q12.20.html

12.23 Why does everyone say not to use gets()?
http://www.*-*-*.com/ ~scs/C-faq/q12.23.html

Last, it's not nice to include such a big source-code.
Some people read this over slow modem-lines. Even when
they're not interested it takes them to long.
--
Marco.
---------------------
Swearing is the only language spoken proficiently by programmers.



Tue, 18 Apr 2000 03:00:00 GMT  
 gets() and fgets() Not Working Properly - Source Included

On Fri, 31 Oct 1997 10:05:42 -0800, Raymond Tompkins

Quote:

>I've tried gets() and almost everyone suggested I use fgets().
>I did but I still get the same result.  Specifically, when I
>select (1) to Add Customer, I get the following:

>***

>Enter Customer information

>Enter the Customer ID number: Enter the name of the Customer:

>***

>In other words, it skips over the first step to enter the
>Customer ID number.

>Why?
...
>     puts("Enter Customer information\n");  
>     printf("Enter the Customer ID number: ");
>     fgets(info.custID,12,stdin);                  
>     printf("Enter the name of the Customer: ");
>     fgets(info.name,24,stdin);          
>     printf("Enter the address line 1: ");
>     fgets(info.addr1,24,stdin);
>     printf("Enter the address line 2: ");
>     fgets(info.addr2,24,stdin);
>     printf("Enter the City and State: ");
>     fgets(info.cityst,24,stdin);
>     printf("Enter the Zipcode: ");
>     fscanf(stdin,"%d", &info.Zipcode);
>     getslot();
>     fwrite(&info, sizeof(info), 1, fp);
>     fclose(fp);
>     getslots();
>return 1;
>}

I'm not sure whether this is what's causing your problem, but since an
implementation is allowed to have stdout open as a line-buffered stream,
for portability it's best to call fflush(stdout) after a printf that
doesn't terminate with a newline.  Either that, or setbuf(stdout,NULL)
before the first use of stdout.

Also, fgets(), unlike gets(), copies the newline character into the
string, so you should add some code to replace the newline with a '\0',
and also to read to the end of the line in case the line is longer than
the array you're reading it into.

And as a matter of style, I hate hardcoding numbers into my code as
you've done in your fgets() calls.  I would write

   fgets(info.custID,12,stdin);

as

   fgets(info.custID, sizeof info.custID, stdin);

for example.
--

Kenan Systems Corporation



Tue, 18 Apr 2000 03:00:00 GMT  
 gets() and fgets() Not Working Properly - Source Included

I've tried gets() and almost everyone suggested I use fgets().
I did but I still get the same result.  Specifically, when I
select (1) to Add Customer, I get the following:

***

Enter Customer information

Enter the Customer ID number: Enter the name of the Customer:

***

In other words, it skips over the first step to enter the
Customer ID number.

Why?

Many thanks in advance.  

Raymond

anti-spam.  To reply directly, remove the 1 in sierra.

***

/*BUSWORK3*/
#include <stdio.h>
#include <io.h>                      /** added **/
#include <stdlib.h>                  /** added **/
#include <string.h>                  /** added **/
#define FILENAME "Custfile"
#define TEMPFILE "Temp"
#define MAX 20
                                     /** function decl **/
int main(void);
int addcust(void);
int delcust(void);
int chcust(void);
int chloc(void);
int sort(void);
int locate(void);
int plist(void);
int showcust(void);
int nofind(void);
int openwr(void);
int getslot(void);
int getslots(void);
FILE *fp, *tp, *printer;
struct Customer
 {
  char  custID[12];                  /** added **/
  char  name[24];
  char  addr1[24];                   /** chng to addr1 **/
  char  addr2[24];                   /** chng to addr2 **/
  char  cityst[24];                  /** added **/
  int  Zipcode;                      /** chng cost to Zipcode **/    
  int  number;
 } info;
int slots[MAX];
int count;
main()
{
     char select;
     getslots();
     do
     {
     puts("     CompuWiz Customer Database\n");
     puts("1  Add Customer\n");
     puts("2  Delete Customer\n");
     puts("3  Edit Customer Information\n");
     puts("4  Change Customer Location\n");
     puts("5  Sort Customer Listing\n");
     puts("6  Locate Customer\n");
     puts("7  Print List\n");
     puts("8  Exit Program\n");
     printf("Please enter selections: ");
     select = getchar();
     putchar('\n');
     switch(select)
     {
     case '1' :
          addcust();
          break;
     case '2':
          delcust();
          break;
     case '3':
          chcust();
          break;
     case '4':
          chloc();
          break;
     case '5':
          sort();
          break;
     case '6':
          locate();
          break;
     case '7':
          plist();
          break;
     case '8':
           break;
     default:
          puts("Invalid entry, try again\n\n");
     }
     }
     while(select!='8');
     return(0);

Quote:
}

int addcust(void)
{
     int pause;
     if(count>=MAX)
     {
     puts("Sorry. The Customer Base is full\n");
     pause=getchar();
     return 1;
     }
     if((fp = fopen(FILENAME,"a")) == NULL)
     {
          printf("Can't open the file %s\n",FILENAME);
          exit(EXIT_FAILURE);
     }
     puts("Enter Customer information\n");  
     printf("Enter the Customer ID number: ");
     fgets(info.custID,12,stdin);                  
     printf("Enter the name of the Customer: ");
     fgets(info.name,24,stdin);          
     printf("Enter the address line 1: ");
     fgets(info.addr1,24,stdin);
     printf("Enter the address line 2: ");
     fgets(info.addr2,24,stdin);
     printf("Enter the City and State: ");
     fgets(info.cityst,24,stdin);
     printf("Enter the Zipcode: ");
     fscanf(stdin,"%d", &info.Zipcode);
     getslot();
     fwrite(&info, sizeof(info), 1, fp);
     fclose(fp);
     getslots();
return 1;

Quote:
}

int delcust(void)
{    /*****                  
     char  delname[24];
     char  fflag;
     fflag='n';
     openrw();
     puts("Delete Customer Function\n");
     printf("Please enter the name of the Customer: ");
     gets(delname);
     while(fread(&info, sizeof(info), 1, fp)==1)
     {
          if(strcmp(info.name, delname) != 0)
          fwrite(&info, sizeof(info), 1, tp);          
          else
          fflag='y';
     }
          fclose(fp);
          fclose(tp);    
         if(fflag=='n')
          nofind();
          else
          {
          openwr();
               while(fread(&info, sizeof(info), 1, tp)==1)
               fwrite(&info, sizeof(info), 1, fp);              
               fclose(fp);
               fclose(tp);
               }
getslots();     *****/
return 1;

Quote:
}

int chcust(void)
{    /*****
     char  chname[24];
     char  fflag;
     int pause;
     fflag='n';
     openrw();
     puts("Change Customer Information\n");
     printf("Please enter the name of the Customer: ");
     gets(chname);
     while(fread(&info, sizeof(info), 1, fp)==1)
         {
         if(strcmp(info.name,chname)!=0)
         fwrite(&info, sizeof(info), 1, tp);      
         else
          {
               fflag='y';
               puts("Old Data\n");
               showdisc();
               puts("New Data\n");
               printf("Enter the Customer ID: ");
               gets(info.custID);
               printf("Enter the name of the Customer: ");
               gets(info.name);
               printf("Enter address line 1:");
               gets(info.addr1);
               printf("Enter address line 2:");
               gets(info.addr2);
               printf("Enter the city and state: ");
               gets(info.cityst);
               printf("Enter the Zipcode:");
               scanf("%d", &info.Zipcode);
               if(count>=MAX)
               {
               puts("Sorry. You cannot change the location\n");
               pause=getchar();
               }
               else
              {
               getslot();
               }

               fwrite(&info, sizeof(info), 1, tp);
               }
          }
     fclose(fp);
     fclose(tp);    
     if(fflag=='n')
          nofind();
               else
               {
               openwr();
               while(fread(&info, sizeof(info), 1, tp)==1)
               fwrite(&info, sizeof(info), 1, fp);              
               fclose(fp);
               fclose(tp);
               }
     getslots();        *****/
return 1;

Quote:
}

int chloc(void)
{    /*****
     char  chname[24];
     char  fflag;
     int pause;
     fflag='n';
     if(count>=MAX)
          {
          puts("Sorry. You cannot change the location\n");
          pause=getchar();
          return;
          }
     openrw();
     puts("Change Customer Information\n");
     printf("Please enter the name of the Customer: ");
     gets(chname);
     while(fread(&info, sizeof(info), 1, fp)==1)
     {
          if(strcmp(info.name,chname)!=0)
          fwrite(&info, sizeof(info), 1, tp);          
          else
          {
          fflag='y';
          puts("Old Data\n");
          showdisc();
          puts("\nNew Location\n");
          getslot();
          fwrite(&info, sizeof(info), 1, tp);
          }
     }
          fclose(fp);
          fclose(tp);    
          if(fflag=='n')
               nofind();
          else
               {
          openwr();
               while(fread(&info, sizeof(info), 1, tp)==1)
               fwrite(&info, sizeof(info), 1, fp);              
               fclose(fp);
               fclose(tp);
          }
          getslots();   *****/
return 1;
Quote:
}

int locate(void)
{    /*****
     char name[24];
     char  fflag, pause;
     fflag='n';
     if((fp = fopen(FILENAME,"r")) == NULL)
     {
          printf("Can't open the file %s\n",FILENAME);
          exit(EXIT_FAILURE);
     }
     puts("Find Customer Information\n");
     printf("Please enter the name of the Customer: ");
     gets(name);
     while(fread(&info, sizeof(info), 1, fp)==1)
          {
          if(strcmp(info.name,name)==0)
          {
          fflag='y';
          showdisc();
          printf("Press Enter to continue");
          pause=getchar();
          putchar('\n');
          }    
          }
          fclose(fp);
          fclose(tp);    
          if(fflag=='n')
           nofind();    *****/
return 1;

Quote:
}

int plist(void)
{

     if((fp = fopen(FILENAME,"r")) == NULL)
      {
          printf("Can't open the file %s\n",FILENAME);
          exit(EXIT_FAILURE);
      }
     if((printer = fopen("prn","w")) == NULL)
      {
          printf("Something is wrong with the printer\n");
          fclose(fp);
          exit(EXIT_FAILURE);
      }
     while(fread(&info, sizeof(info), 1, fp)==1)
     {
     fprintf(printer,"Customer ID:      %s\n",info.custID);
     fprintf(printer,"Customer Name     %s\n",info.name);
     fprintf(printer,"Address Line 1:   %s\n",info.addr1);
     fprintf(printer,"Address Line 2:   %s\n",info.addr2);
     fprintf(printer,"City and State:   %s\n",info.cityst);
     fprintf(printer,"Zipcode:          %d\n",info.Zipcode);
     fprintf(printer,"Location:         %d\n",info.number);
     fprintf(printer,"\n\n");
     }
     fclose(printer);
     fclose(fp);
return 1;

Quote:
}

int sort(void)
{    /*****
     struct Customer temp[MAX];
     int index, loop1, loop2, endloop;
     loop1=0;
     loop2=0;
     endloop=0;

     index = 0;
     if((fp = fopen(FILENAME,"r")) == NULL)
      {
     printf("Can't open the file %s\n",FILENAME);    
     exit(EXIT_FAILURE);
      }
     while(fread(&info, sizeof(info), 1, fp)==1)
     {
          temp[index]=info;
          index++;

     }
     fclose(fp);
     if((fp = fopen(FILENAME,"w")) == NULL)
      {
          printf("Can't open the file %s\n",FILENAME);    
          exit(EXIT_FAILURE);
      }
     for(loop1=1;loop1<MAX+1;loop1++)
          {
               for(loop2=0;loop2<count;loop2++)
               if(temp[loop2].number==loop1)
               {
               fwrite(&temp[loop2], sizeof(temp[loop2]), 1, fp);
               endloop++;
               }
     if(endloop==count)
          break;
     }
     fclose(fp);        *****/
return 1;

Quote:
}

int showcust(void)
{
     printf("Customer ID:         %s\n",info.custID);
     printf("Customer Name        %s\n",info.name);
     printf("Address Line 1:      %s\n",info.addr1);
     printf("Address Line 2:      %s\n",info.addr2);
     printf("City and State:      %s\n",info.cityst);
...

read more »



Tue, 18 Apr 2000 03:00:00 GMT  
 gets() and fgets() Not Working Properly - Source Included


 asked:

|> I've tried gets() and almost everyone suggested I use fgets().
|> I did but I still get the same result.  Specifically, when I
|> select (1) to Add Customer, I get the following:
|>
|> ***
|>
|> Enter Customer information
|>
|> Enter the Customer ID number: Enter the name of the Customer:
|>
|> ***
|>
|> In other words, it skips over the first step to enter the
|> Customer ID number.
|>
|> Why?

  Because you didn't manage to switch over to using 'fgets()' for
  _all_ of your user input. I have indicated below the root cause
  of your difficulty.

|>
|> Many thanks in advance.  
|>
|> Raymond
|>

  <*snippage*>

|> main()
|> {
|>      char select;
|>      getslots();
|>      do
|>      {
|>      puts("     CompuWiz Customer Database\n");
|>      puts("1  Add Customer\n");
|>      puts("2  Delete Customer\n");
|>      puts("3  Edit Customer Information\n");
|>      puts("4  Change Customer Location\n");
|>      puts("5  Sort Customer Listing\n");
|>      puts("6  Locate Customer\n");
|>      puts("7  Print List\n");
|>      puts("8  Exit Program\n");
|>      printf("Please enter selections: ");

  This is unrelated to your problem, but you _could_ accomplish the
  above a good deal more efficiently by:

        printf("     CompuWiz Customer Database\n"
               "1  Add Customer\n"
               "2  Delete Customer\n"
               "3  Edit Customer Information\n"
               "4  Change Customer Location\n"
               "5  Sort Customer Listing\n"
               "6  Locate Customer\n"
               "7  Print List\n"
               "8  Exit Program\n"
               "Please enter selections: ");

  which replaces 10 function calls by 1 ...

|>      select = getchar();

  ... that was it ... Notice that you choose to add a customer by
  typing "1\n", the above call to 'getchar()' returns the '1' and
  leaves the '\n' sitting in stdin's input buffer ...

|>      putchar('\n');
|>      switch(select)
|>      {
|>      case '1' :
|>           addcust();
|>           break;
        .
        .
        .
|>      default:
|>           puts("Invalid entry, try again\n\n");
|>      }
|>      }
|>      while(select!='8');
|>      return(0);
|> }
|>
|> int addcust(void)
|> {
|>      int pause;
|>      if(count>=MAX)
|>      {
|>      puts("Sorry. The Customer Base is full\n");
|>      pause=getchar();
|>      return 1;
|>      }
|>      if((fp = fopen(FILENAME,"a")) == NULL)
|>      {
|>           printf("Can't open the file %s\n",FILENAME);
|>           exit(EXIT_FAILURE);
|>      }
|>      puts("Enter Customer information\n");  
|>      printf("Enter the Customer ID number: ");
|>      fgets(info.custID,12,stdin);                  

  ... this call to 'fgets()' finds the leftover '\n' in the input
  buffer, copies it into 'info.custID' and returns all fat, dumb
  and happy ...

|>      printf("Enter the name of the Customer: ");
|>      fgets(info.name,24,stdin);          
        .
        .
        .
|> return 1;
|> }
|>

  <*major snippage*>

  The easiest fix for yur problem is to replace the line "select=getchar();"
  by

        fgets(buffer,sizeof buffer,stdin);
        select = buffer[0];

  where 'buffer' is an array of 'char's of an appropriate size.

--
 Ed Hook                              |       Copula eam, se non posit
 MRJ Technology Solutions, Inc.       |         acceptera jocularum.
 NAS, NASA Ames Research Center       | I can barely speak for myself, much



Thu, 20 Apr 2000 03:00:00 GMT  
 
 [ 4 post ] 

 Relevant Pages 

1. fscanf or fgets not working properly?

2. CFile not working properly, can't figure out why (last message not sent properly)

3. fgets/gets not recognized

4. fgets/gets not recognized![Help]

5. Parameters not getting to the Sink properly

6. Float type not getting calculated properly in a program

7. Tab key to tab between controls does not work properly

8. Scroll bars not working properly

9. AtlReportError not working in ATL 7.0 (Injected code doesn't handle ErrorInfo properly)

10. Links not working properly in the Object Browser

11. mouse_event for mouse move is not working properly.

12. fgets and sscanf not working as expected

 

 
Powered by phpBB® Forum Software