User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the C section within the Software Development category of DaniWeb, a massive community of 370,613 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,116 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our C advertiser:
View Poll Results: Is my query a dumb one?
Yes! 4 50.00%
Ofcourse! 1 12.50%
Not at all! 0 0%
You're a nice guy! 3 37.50%
Voters: 8. You may not vote on this poll

Views: 2468 | Replies: 15 | Solved
Reply
Join Date: May 2007
Location: Melbourne
Posts: 12
Reputation: brightmohan is an unknown quantity at this point 
Rep Power: 2
Solved Threads: 0
brightmohan brightmohan is offline Offline
Newbie Poster

Question C Program where gets(), getchar(), are not working.

  #1  
May 5th, 2007
Hello Geeks!

I have tried real hard trying to figure out the solution for why the getchar() and fputs() arent working in my program. I have already wasted so much time thinking and debugging about it and here I am after registering wid DANIWEB for the first time.

I will be attaching my program PROGRAM.C below, please help me out why in the function getline() the getchar() isnt working?? It is not accepting values from the user.

I will also be attaching another program SAMPLE.C which involves the same function called getline() which works in a perfect manner.

Please have the file LOV.TXT in the program directory and execute.

All help and suggestions appreciated.

Thank you.
Mohan!
Last edited by brightmohan : May 5th, 2007 at 12:10 pm.
Attached Files
File Type: c sample.C (586 Bytes, 2 views)
File Type: txt lov.txt (201 Bytes, 1 views)
File Type: c program.c (19.5 KB, 4 views)
You have to let it all go Neo! Fear, Doubt, Disbelief!
AddThis Social Bookmark Button
Reply With Quote  
Join Date: Aug 2005
Posts: 4,588
Reputation: iamthwee is a jewel in the rough iamthwee is a jewel in the rough iamthwee is a jewel in the rough iamthwee is a jewel in the rough 
Rep Power: 15
Solved Threads: 290
iamthwee's Avatar
iamthwee iamthwee is offline Offline
Industrious Poster

Re: C Program where gets(), getchar(), are not working.

  #2  
May 5th, 2007
post your code here otherwise ppl will not download it.
Member of: F-ugly code club

Join today don't delay!
Reply With Quote  
Join Date: Aug 2005
Location: near St Louis, Missouri, USA
Posts: 10,104
Reputation: Ancient Dragon has much to be proud of Ancient Dragon has much to be proud of Ancient Dragon has much to be proud of Ancient Dragon has much to be proud of Ancient Dragon has much to be proud of Ancient Dragon has much to be proud of Ancient Dragon has much to be proud of Ancient Dragon has much to be proud of Ancient Dragon has much to be proud of 
Rep Power: 34
Solved Threads: 806
Moderator
Featured Poster
Ancient Dragon's Avatar
Ancient Dragon Ancient Dragon is offline Offline
Most Valuable Poster

Re: C Program where gets(), getchar(), are not working.

  #3  
May 5th, 2007
there is a lot easier way to get a line from the keyboard than what you coded in the program.c file. fgets() will do all that nasty work for you, like this -- notice there are no loops and only 1 line of code other than the buffer declaration.

  1. char line[100];
  2. fgets(line,sizeof(line),stdin);

BTW: your question is ok, its the poll that is a dumb one.
Last edited by Ancient Dragon : May 5th, 2007 at 12:00 pm.
'Politics' is made up of two words, 'poli,' which is Greek for 'many,' and 'tics,' which are blood-sucking insects.
- Gore Vidal
Being ignorant is not so much a shame as being unwilling to learn. - Benjamin Franklin
Reply With Quote  
Join Date: May 2007
Location: Melbourne
Posts: 12
Reputation: brightmohan is an unknown quantity at this point 
Rep Power: 2
Solved Threads: 0
brightmohan brightmohan is offline Offline
Newbie Poster

Re: C Program where gets(), getchar(), are not working.

  #4  
May 5th, 2007
Originally Posted by iamthwee View Post
post your code here otherwise ppl will not download it.
Okie Dokie! Let me do that!

Thank You very much.
You have to let it all go Neo! Fear, Doubt, Disbelief!
Reply With Quote  
Join Date: May 2007
Location: Melbourne
Posts: 12
Reputation: brightmohan is an unknown quantity at this point 
Rep Power: 2
Solved Threads: 0
brightmohan brightmohan is offline Offline
Newbie Poster

News Re: C Program where gets(), getchar(), are not working.

  #5  
May 5th, 2007
If you're having issues with downloading the code you can see it here.

The PROGRAM.C code:
 

#define TRUE 1
#define MAX_REC_LEN 1024
#define EOF_MARKER 26 
#define LF 10
#define CR 13


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
//#include<curses.h>

int getline(char line[], int max)
{
int nch = 0;
int c;
max = max - 1;            /* leave room for '\0' */

while((c = getchar()) != '\0')
    {
    if(c == '\n')
        break;

    if(nch < max)
        {
        line[nch] = c;
        nch = nch + 1;
        }
    }

if(c == EOF && nch == 0)
    return EOF;

line[nch] = '\0';
return nch;
}



void HR(int iLen)
{
  int i;

  for (i = 0; i < iLen; i++)
    printf("-");

  printf("\n");
  return;

} /* end HR() */



/******************************************************************************/
int search_delete(FILE *fp,char *szReadLine,  long lLineCount,    long lLineLen, long lThisFilePos, long *lLastFilePos, int  isFilePosErr, char *lookup_field, int del_choice)
/******************************************************************************/
/* Use:       Details for current line                                   */
/*                                                                            */
/* Arguments: char *szReadLine   = Read buffer containg text line             */
/*            long  lLineCount   = Current line number                        */
/*            long  lLineLen     = Current line length                        */
/*            long  lThisFilePos = Offset of start of current line            */
/*            long *lLastFilePos = Offset of end of current line              */
/*            int   isFilePosErr = True if start of current line is not       */
/*                                   1 greater than end of last line          */
/*                                                                            */
/* Return:    int 1 or 0 if the record is deleted or not                                                            */
/******************************************************************************/
{
  int flag=0;

  char *cPtr; /* Pointer to current character */

  int i=-1,j=-1,k=-1;

  char *title[20];
  char *fname[20];
  char *lname[20];
  char *price[10];
  char *repcost[10];

  int count1=0, count2=0 ,count3=0, count4=0,count5=0;
  int p=0;
  int m=-1;
  int del_count=0;
  int l=-1;

  int count;
  char c;

  int p_loop=0;

 //FILE* fp1;
 //fp1=fopen("lov1.txt","w+");

  //printf("Book ID: %ld",lLineNumber);

  char *temp3;
  char *tit;

  cPtr = szReadLine; /* Point to start of string */




  /* Print the characters, including null terminator */
  for (cPtr = szReadLine; cPtr <= szReadLine + lLineLen; cPtr++)
  {
    if(del_count==0)
     {
      if(*cPtr=='|')
       {
        //printf("A | encountered");
        del_count++;
        title[++i]='\0';
        printf("\n\nThe value in Title is: %s",title);
        *cPtr++;
        //break;
         }
         else
          {
           title[++i]=*cPtr;
           count1=i+1;
           }
       }//end of del_count0

    if(del_count==1)
     {
      if(*cPtr=='|')
       {
        //printf("A | encountered");
        del_count++;
        fname[++j]='\0';
        *cPtr++;
        //break;
         }
         else
          {
           fname[++j]=*cPtr;
           count2=j+1;
          // printf("Character Count: %d",count2);
           }
       }//end of del_count0

    if(del_count==2)
     {
      if(*cPtr=='|')
       {
        //printf("A | encountered");
        del_count++;

        lname[++k]='\0';
        printf("\n\nThe value in Last Name is: %s",lname);
        *cPtr++;
        //break;
         }
         else
          {
           lname[++k]=*cPtr;
           count3=k+1;
           }
       }//end of del_count0

    if(del_count==3)
     {
      if(*cPtr=='|')
       {
        //printf("A | encountered");
        del_count++;
        price[++l]='\0';
        printf("\n\nThe value in Price is: %s",price);
        *cPtr++;
        //break;
         }
         else
          {
           price[++l]=*cPtr;
           count4=l+1;
           }
       }//end of del_count

    if(del_count==4)
     {
      if(*cPtr=='\0')
       {
        //printf("A | encountered");
        del_count++;
        repcost[++m]='\0';
        printf("\n\nThe value in Replacement Cost is: %s",repcost);
        *cPtr++;
        //break;
         }
         else
          {
           repcost[++m]=*cPtr;
           count5=m; //no +1 cos' its the terminator char
           }
       }//end of del_count0

  } /* end for (cPtr) */

printf("CCC: %d   %d  %d  %d  %d ", count1,count2,count3,count4,count5);

for (p=0; p<count1; p++)
{
    title[p] = tolower(title[p]);

    printf("\n--%c--",title[p]);
    //lookup_field[p]=tolower(lookup_field[p]);
    if(title[p]==lookup_field[p])
     {
     printf("YES");
      }

}

for (p=0; p<count2; p++)
{
    fname[p] = tolower(fname[p]);

   // printf("\n--%c--",fname[p]);
    //lookup_field[p]=tolower(lookup_field[p]);
}


for (p=0; p<count3; p++)
{
    lname[p] = tolower(lname[p]);

   // printf("\n--%c--",fname[p]);
    //lookup_field[p]=tolower(lookup_field[p]);
}


for (p=0; p<count4; p++)
{
    price[p] = tolower(price[p]);

   // printf("\n--%c--",fname[p]);
    //lookup_field[p]=tolower(lookup_field[p]);
}


for (p=0; p<count5; p++)
{
    repcost[p] = tolower(repcost[p]);

   // printf("\n--%c--",fname[p]);
    //lookup_field[p]=tolower(lookup_field[p]);


}

//printf("%s\n %s\n",fname,lookup_field);

 switch(del_choice)
  {
   case 1:
          //count= strncmp(lookup_field,title,sizeof(title));

           if(count==0)
           {
                 printf("YES YES");
        }


      if(*title==*lookup_field)
        {

       return(1);
        }
      else
       {
         return(0);
         }
       break;
   case 2:
      if(*fname==*lookup_field)
       {
        printf("\n\n YEAH BABY THEY ARE EQUAL");
        return(1);
        }
        else
         {
          return(0);
           }
        break;
   case 3:
      if(*lname==*lookup_field)
       {
        printf("\n\n YEAH BABY THEY ARE EQUAL");
        return(1);
        }
        else
         {
          return(0);
          }
       break;

   } //end of switch case


  printf("\n");

} /* end of function search_delete()*/




/******************************************************************************/
void PrintLine(char *szReadLine,  long lLineCount,    long lLineLen,
               long lThisFilePos, long *lLastFilePos, int  isFilePosErr)
/******************************************************************************/
/* Use:       Print detail for current line                                   */
/*                                                                            */
/* Arguments: char *szReadLine   = Read buffer containg text line             */
/*            long  lLineCount   = Current line number                        */
/*            long  lLineLen     = Current line length                        */
/*            long  lThisFilePos = Offset of start of current line            */
/*            long *lLastFilePos = Offset of end of current line              */
/*            int   isFilePosErr = True if start of current line is not       */
/*                                   1 greater than end of last line          */
/*                                                                            */
/* Return:    void                                                            */
/******************************************************************************/
{
  char *cPtr; /* Pointer to current character */

  int del_count=0;
  HR(80); /* Print a separator line */
  printf("Book ID: %ld, Length=%#x (dec %ld)\n",lLineCount, (int)lLineLen, lLineLen); /* See PrintHeader() for an    */
                                               /* explanation of why the cast */
                                               /* is needed.                  */
//  printf(" Offset:");

  cPtr = szReadLine; /* Point to start of string */

  //if (isFilePosErr)                 /* Indicates offset error */
   // printf("*%2x", lThisFilePos++);    /* Print '*' plus starting offset */
 // else                              /* Offset okay */
   // printf("%3x", lThisFilePos++);     /* Just print starting offset */

  //for (++cPtr; cPtr < szReadLine + lLineLen; cPtr++) /* Remaining offsets */
    //printf("%3x", lThisFilePos++);

  //if (lLastFilePos != NULL)           /* Set end position if arg passed */
    //*lLastFilePos = lThisFilePos - 1;

  //printf("\n Hex:   ");

  /* Print the hex values, including null terminator */
  //for (cPtr = szReadLine; cPtr <= szReadLine + lLineLen; cPtr++)
    //printf("%3x", *cPtr);


  //printf("\n Char:  ");

     if(del_count==0)
    {
    printf("\n Title: ");
     }
  /* Print the characters, including null terminator */
  for (cPtr = szReadLine; cPtr <= szReadLine + lLineLen; cPtr++)
  {

    switch (*cPtr)
    {
      case 0:                 /* Null terminator */
    //printf(" \\0");
        break;

      case CR:                /* Carriage return */
    //printf(" cr");
        break;

      case LF:                /* Line feed */
    //printf(" lf");
        break;

      case EOF_MARKER:        /* DOS end-of-file marker */
    //printf(" em");
    break;

      case '|':
     //printf("|");
         del_count++;
      if(del_count==1)
        {
         printf("\n Author: ");

         }
         if(del_count==2)
          {
        printf(", ");
           }
         if(del_count==3)
          {
           printf("\n Year: ");
           }

           if(del_count==4)
        {
          printf("\n Replacement Cost: ");
         }

     break;

      default:                /* A 'real' character */
    //printf("%3c", *cPtr);
    printf("%c",*cPtr);
        break;

    } /* end switch (*cPtr) */

  } /* end for (cPtr) */

  printf("\n");
  return;

} /* end PrintLine()*/


load_catalogue(FILE *input)
{

  int   isNewline;              /* Boolean indicating we've read a CR or LF */
  long  lFileLen;               /* Length of file */
  long  lIndex;                 /* Index into cThisLine array */
  long  lLineCount;             /* Current line number */
  long  lLineLen;               /* Current line length */
  long  lStartPos;              /* Offset of start of current line */
  long  lTotalChars;            /* Total characters read */
  char  cThisLine[MAX_REC_LEN]; /* Contents of current line */
  char *cFile;                  /* Dynamically allocated buffer (entire file) */
  char *cThisPtr;               /* Pointer to current position in cFile */

  fseek(input, 0L, SEEK_END);  /* Position to end of file */
  lFileLen = ftell(input);     /* Get file length */
  rewind(input);               /* Back to start of file */

  cFile = calloc(lFileLen + 1, sizeof(char));

  if(cFile == NULL )
  {
    printf("\nInsufficient memory to read file.\n");
    return 0;
  }

  fread(cFile, lFileLen, 1, input); /* Read the entire file into cFile */

  lLineCount  = 0L;
  lTotalChars = 0L;

  cThisPtr    = cFile;              /* Point to beginning of array */

  while (*cThisPtr)                 /* Read until reaching null char */
  {
    lIndex    = 0L;                 /* Reset counters and flags */
    isNewline = 0;
    lStartPos = lTotalChars;

    while (*cThisPtr)               /* Read until reaching null char */
    {
      if (!isNewline)               /* Haven't read a CR or LF yet */
      {
        if (*cThisPtr == CR || *cThisPtr == LF) /* This char IS a CR or LF */
          isNewline = 1;                        /* Set flag */
      }

      else if (*cThisPtr != CR && *cThisPtr != LF) /* Already found CR or LF */
        break;                                     /* Done with line */

      cThisLine[lIndex++] = *cThisPtr++; /* Add char to output and increment */
      ++lTotalChars;

    } /* end while (*cThisPtr) */

    cThisLine[lIndex] = '\0';     /* Terminate the string */
    ++lLineCount;                 /* Increment the line counter */
    lLineLen = strlen(cThisLine); /* Get length of line */

    /* Print the detail for this line */
    PrintLine(cThisLine, lLineCount, lLineLen, lStartPos, NULL, 0);

  } /* end while (cThisPtr <= cEndPtr) */

  HR(80); /* Print a separator line */

  printf("Length of file array=%#x (dec %d)\n", strlen(cFile), strlen(cFile));

  return 1;

}//End of function load_catalogue()

/*Load and delete function for various choices*/
load_delete(FILE *input,char *field,int choice)
{

  int   isNewline;              /* Boolean indicating we've read a CR or LF */
  long  lFileLen;               /* Length of file */
  long  lIndex;                 /* Index into cThisLine array */
  long  lLineCount;             /* Current line number */
  long  lLineLen;               /* Current line length */
  long  lStartPos;              /* Offset of start of current line */
  long  lTotalChars;            /* Total characters read */
  char  cThisLine[MAX_REC_LEN]; /* Contents of current line */
  char *cFile;                  /* Dynamically allocated buffer (entire file) */
  char *cThisPtr;               /* Pointer to current position in cFile */
  int found=0;
  char *buffer;
  FILE *file1;

  fseek(input, 0L, SEEK_END);  /* Position to end of file */

  lFileLen = ftell(input);     /* Get file length */
  rewind(input);               /* Back to start of file */


  cFile = calloc(lFileLen + 1, sizeof(char));

  buffer= calloc(lFileLen + 1, sizeof(char));

  if(cFile == NULL )
  {
    printf("\nInsufficient memory to read file.\n");
    return 0;
  }

  fread(cFile, lFileLen, 1, input); /* Read the entire file into cFile */
  fclose(input);

  file1=fopen("lov1.txt","w+");

  lLineCount  = 0L;
  lTotalChars = 0L;

  cThisPtr    = cFile;              /* Point to beginning of array */

  while (*cThisPtr)                 /* Read until reaching null char */
  {
    lIndex    = 0L;                 /* Reset counters and flags */
    isNewline = 0;
    lStartPos = lTotalChars;

    while (*cThisPtr)               /* Read until reaching null char */
    {
      if (!isNewline)               /* Haven't read a CR or LF yet */
      {
        if (*cThisPtr == CR || *cThisPtr == LF) /* This char IS a CR or LF */
          isNewline = 1;                        /* Set flag */
      }

      else if (*cThisPtr != CR && *cThisPtr != LF) /* Already found CR or LF */
        break;                                     /* Done with line */

      cThisLine[lIndex++] = *cThisPtr++; /* Add char to output and increment */
      ++lTotalChars;

    } /* end while (*cThisPtr) */

    cThisLine[lIndex] = '\0';     /* Terminate the string */
    ++lLineCount;                 /* Increment the line counter */
    lLineLen = strlen(cThisLine); /* Get length of line */

    /* Print the detail for this line */
   // PrintLine(cThisLine, lLineCount, lLineLen, lStartPos, NULL, 0);

 found=search_delete(input, cThisLine, lLineCount, lLineLen, lStartPos, NULL, 0,field,choice);

  if(found==1)
   {
    //dont write it to the buffer
    printf("One Matching Record Found: Deleted");
    }
    else {
       //Write that line to the buffer.
    fprintf(file1,"%s",cThisLine);

      }

  } /* end while (cThisPtr <= cEndPtr) */

  HR(80); /* Print a separator line */

  printf("Length of file array=%#x (dec %d)\n", strlen(cFile), strlen(cFile));

  return 1;

} //end of function load_delete()

save_catalogue(char *filename, char *title, char *fname, char *lname, int year, float repl_cost )
{

    
}//end of function save_catalogue()

sort_display(char *filename, int flag)
{

} //end of the sort_display() function    

void main()

{

int choice,del_choice;
char *cat_file="Catalogue.txt";
FILE *fp,*fp1;
int i;

char  *del_cat,au_fname[20], au_lname[20];
char new_cat_file[30],new_title[30], new_fau[30], new_lau[30];

int new_year,  sort_choice;

float new_rep_cost;

int sort_flag;

      while(TRUE)
    {
     
        printf("***Library Catalogue***\n\n");
        printf("Select your option please:\n\n");
        printf("1> Load Catalogue\n");    
        printf("2> Delete book from the Catalogue\n");
        printf("3> Save Catalogue[Inserting a new item]\n");
        printf("4> Sort & Display Catalogue\n");
        printf("5> Quit\n");

        scanf("%d",&choice);    

        switch(choice)
        {
            case 1: printf("Load Catalogue\n");
                printf("Enter the name of the catalogue file to load:\n");
                scanf("%s",cat_file);
                fp=fopen(cat_file, "r+");
                if(fp==NULL)
                 {
                  printf("Error Opening The Catalogue File\n\n");
                  break;
                 }
                 else
                 {
                load_catalogue(fp);
                }
                 fclose(fp); //close the file stream

                break;

            case 2: printf("Delete book from the Catalogue\n");
                printf("Please enter the name of the Catalogue File: ");
                scanf("%s",new_cat_file);
                fp1=fopen(new_cat_file, "r+");
                if(fp1==NULL)
                 {
                  printf("Error Opening The Catalogue File\n\n");
                  break;
                 }
                printf("Press 1 to delete a book by Title\n");
                printf("Press 2 to delete a book by Author's First Name\n");
                printf("Press 3 to delete a book by Author's Last Name\n");
                printf("Your Choice please: ");
                scanf("%d",&del_choice);

                switch(del_choice)
                {
                case 1:
                printf("Please enter the book title to delete: ");
                //scanf("%s",del_cat);
                getline(del_cat,30);
                printf("%s",del_cat);


                for(i=0;i<=30;i++)
                 {
                del_cat[i] = tolower(del_cat[i]);
                printf("%c",del_cat[i]);
                  }

                load_delete(fp1,del_cat,del_choice);

                break;

                case 2:
                printf("Enter the Author's First Name to delete books: ");
                scanf("%s",au_fname);
                 for(i=0;i<=20;i++)
                 {
                au_fname[i] = tolower(au_fname[i]);
                  }
                load_delete(fp1,au_fname,del_choice);
                break;

                case 3:
                printf("\nEnter the Author's Last Name: ");
                scanf("%s",au_lname);
                for(i=0;i<=20;i++)
                 {
                au_lname[i] = tolower(au_lname[i]);
                  }
                load_delete(fp1,au_lname,del_choice);
                break;

                default:
                   printf("Sorry Wrong Choice!");
                   break;
                }

                break;

            case 3: printf("Save Catalogue[Inserting a new item]\n");
                
                printf("Please enter the name of the Catalogue File: ");
                scanf("%s",new_cat_file);
                printf("\nEnter the title of the book: ");
                scanf("%s",new_title);
                printf("\nEnter the Author's First Name: ");
                scanf("%s",new_fau);
                printf("\nEnter the Author's Last Name: ");
                scanf("%s",new_lau);
                printf("\nEnter the Year of Publication: ");
                scanf("%d",&new_year);    
                printf("\nEnter the Replacement Cost: ");
                scanf("%f",&new_rep_cost);
                                         save_catalogue(cat_file,new_title,new_fau,new_lau,new_year,new_rep_cost);
                break;
                
            case 4: printf("Sort & Display Catalogue\n");
                printf("Please slect the sorting order: \n");
                printf("1> By Title\n2> By LastName\n3> By Replacement Cost\n4> By Publication Year\n ");
                scanf("%d",&sort_choice);
                
                switch(sort_choice)
                {
                    case 1: 
                        sort_flag=1;
                        sort_display(cat_file,sort_flag);
                        break;
                    
                            case 2:
                        sort_flag=2;
                        sort_display(cat_file,sort_flag);
                        break;

                    case 3: sort_flag=3;
                        sort_display(cat_file,sort_flag);
                        break;

                    case 4: sort_flag=4;
                        sort_display(cat_file,sort_flag);
                        break;
                        
                    default: printf("Sorry! Invalid Choice.");
                         break;

                } //End of inneer swith case
                 

             case 5: printf("Thank you for using the system :)");
                 exit(0);
                 break;

             default: printf("Sorry! Invalid choice.");
                  break;
                  
            }//End of the main switch case

        } // End of the main While loop which runs infinite            

      } //End of the main() function
Last edited by ~s.o.s~ : May 5th, 2007 at 12:49 pm. Reason: Fixed code tags.
You have to let it all go Neo! Fear, Doubt, Disbelief!
Reply With Quote  
Join Date: Aug 2005
Posts: 4,588
Reputation: iamthwee is a jewel in the rough iamthwee is a jewel in the rough iamthwee is a jewel in the rough iamthwee is a jewel in the rough 
Rep Power: 15
Solved Threads: 290
iamthwee's Avatar
iamthwee iamthwee is offline Offline
Industrious Poster

Re: C Program where gets(), getchar(), are not working.

  #6  
May 5th, 2007
And sample.c and lov.txt?

Please post them as well if you haven't already.
Member of: F-ugly code club

Join today don't delay!
Reply With Quote  
Join Date: May 2007
Location: Melbourne
Posts: 12
Reputation: brightmohan is an unknown quantity at this point 
Rep Power: 2
Solved Threads: 0
brightmohan brightmohan is offline Offline
Newbie Poster

News Re: C Program where gets(), getchar(), are not working.

  #7  
May 5th, 2007
Originally Posted by Ancient Dragon View Post
there is a lot easier way to get a line from the keyboard than what you coded in the program.c file. fgets() will do all that nasty work for you, like this -- notice there are no loops and only 1 line of code other than the buffer declaration.

  1. char line[100];
  2. fgets(line,sizeof(line),stdin);

BTW: your question is ok, its the poll that is a dumb one.


Gosh! Nope! It still doesnt work.....The interpreter jumps at fgets() I dunno why. It doesnt stop to get characters from my Keyboard. Is it because I'm doing it on Laptop??? lol ?

Gosh!! The time is just flying!!!!
You have to let it all go Neo! Fear, Doubt, Disbelief!
Reply With Quote  
Join Date: May 2007
Location: Melbourne
Posts: 12
Reputation: brightmohan is an unknown quantity at this point 
Rep Power: 2
Solved Threads: 0
brightmohan brightmohan is offline Offline
Newbie Poster

News Re: C Program where gets(), getchar(), are not working.

  #8  
May 5th, 2007
Here is the SAMPLE.C where gets() works absolutely fine. I dont understand why it isnt working in PROGRAM.C


  1.  
  2. #include<errno.h>
  3. #include<stdio.h>
  4.  
  5. int getline(char line[], int max)
  6. {
  7. int nch = 0;
  8. int c;
  9. max = max - 1; /* leave room for '\0' */
  10.  
  11. while((c = getchar()) != '\0')
  12. {
  13. if(c == '\n')
  14. break;
  15.  
  16. if(nch < max)
  17. {
  18. line[nch] = c;
  19. nch = nch + 1;
  20. }
  21. }
  22.  
  23. if(c == EOF && nch == 0)
  24. return EOF;
  25.  
  26. line[nch] = '\0';
  27. return nch;
  28. }
  29.  
  30.  
  31. #include <stdio.h>
  32.  
  33. extern int getline(char [], int);
  34.  
  35. main()
  36. {
  37. char line[256];
  38.  
  39. printf("Your names");
  40. getline(line,256);
  41. //while(getline(line, 256) != '\0')
  42. //
  43. printf("you typed \"%s\"\n", line);
  44.  
  45. return 0;
  46. }

I tired the solution posted by geek ANCIENT DRAGON. It is not working too....:
  1. char line[100];
  2. fgets(line,sizeof(line),stdin);
You have to let it all go Neo! Fear, Doubt, Disbelief!
Reply With Quote  
Join Date: May 2007
Location: Melbourne
Posts: 12
Reputation: brightmohan is an unknown quantity at this point 
Rep Power: 2
Solved Threads: 0
brightmohan brightmohan is offline Offline
Newbie Poster

News Re: C Program where gets(), getchar(), are not working.

  #9  
May 5th, 2007
The lov.txt file is:

How to swim|Tina|Turner|1998|1980.90
How to learn C++|Tim|DelMar|1997|2909.89
How to Crawl|Benicio|Tot|1998|1980.90
How to learn Java|All|Gore|1997|2909.89
How to Relax|Earnst|Summers|1889|2039.90


Its the file that you can pass to the PROGRAM.C while executing.
You have to let it all go Neo! Fear, Doubt, Disbelief!
Reply With Quote  
Join Date: Dec 2006
Posts: 1,217
Reputation: Aia is a glorious beacon of light Aia is a glorious beacon of light Aia is a glorious beacon of light Aia is a glorious beacon of light Aia is a glorious beacon of light 
Rep Power: 8
Solved Threads: 83
Aia's Avatar
Aia Aia is offline Offline
Nearly a Posting Virtuoso

Re: C Program where gets(), getchar(), are not working.

  #10  
May 5th, 2007
Originally Posted by brightmohan View Post
Here is the SAMPLE.C where gets() works absolutely fine. I dont understand why it isnt working in PROGRAM.C


  1.  
  2. #include<errno.h>
  3. #include<stdio.h>
  4.  
  5. int getline(char line[], int max)
  6. {
  7. int nch = 0;
  8. int c;
  9. max = max - 1; /* leave room for '\0' */
  10.  
  11. while((c = getchar()) != '\0')
  12. {
  13. if(c == '\n')
  14. break;
  15.  
  16. if(nch < max)
  17. {
  18. line[nch] = c;
  19. nch = nch + 1;
  20. }
  21. }
  22.  
  23. if(c == EOF && nch == 0)
  24. return EOF;
  25.  
  26. line[nch] = '\0';
  27. return nch;
  28. }
  29.  
  30.  
  31. #include <stdio.h>
  32.  
  33. extern int getline(char [], int);
  34.  
  35. main()
  36. {
  37. char line[256];
  38.  
  39. printf("Your names");
  40. getline(line,256);
  41. //while(getline(line, 256) != '\0')
  42. //
  43. printf("you typed \"%s\"\n", line);
  44.  
  45. return 0;
  46. }

I tired the solution posted by geek ANCIENT DRAGON. It is not working too....:
  1. char line[100];
  2. fgets(line,sizeof(line),stdin);

Take a look at this function:

  1. #include <stdio.h>
  2.  
  3. int *getline( char *string, size_t size )
  4. {
  5. size_t i = 0;
  6. for(;;)
  7. {
  8. int ch = fgetc(stdin);
  9. if(ch == '\n' || ch == EOF)
  10. {
  11. break;
  12. }
  13. if(i < size - 1)
  14. {
  15. string[i++] = ch;
  16. }
  17. } /* forever loop end */
  18.  
  19. string[i] = '\0';
  20. return string;
  21. }
"It was the best of times, it was the worst of times, ...it was the spring of hope, it was the winter of despair, ..."
A Tale of Two Cities ~ Charles Dickens
Reply With Quote  
Reply

Only community members can participate in forum threads. You must register or log in to contribute.

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)

 

DaniWeb C Marketplace
Thread Tools Display Modes

Similar Threads