| | |
C Program where gets(), getchar(), are not working.
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 | |||
Thread Solved |
•
•
Join Date: May 2007
Posts: 12
Reputation:
Solved Threads: 0
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!
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 1:10 pm.
You have to let it all go Neo! Fear, Doubt, Disbelief!
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.
BTW: your question is ok, its the poll that is a dumb one.
c Syntax (Toggle Plain Text)
char line[100]; 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 1:00 pm.
Don't PM me with questions -- you might get a nasty PM in response. If you have a question then post it in one of the forums.
•
•
Join Date: May 2007
Posts: 12
Reputation:
Solved Threads: 0
If you're having issues with downloading the code you can see it here.
The PROGRAM.C code:
The PROGRAM.C code:
C Syntax (Toggle Plain Text)
#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 1:49 pm. Reason: Fixed code tags.
You have to let it all go Neo! Fear, Doubt, Disbelief!
•
•
Join Date: May 2007
Posts: 12
Reputation:
Solved Threads: 0
•
•
•
•
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.
c Syntax (Toggle Plain Text)
char line[100]; fgets(line,sizeof(line),stdin);
BTW: your question is ok, its the poll that is a dumb one.
?Gosh!! The time is just flying!!!!
You have to let it all go Neo! Fear, Doubt, Disbelief!
•
•
Join Date: May 2007
Posts: 12
Reputation:
Solved Threads: 0
Here is the SAMPLE.C where gets() works absolutely fine. I dont understand why it isnt working in PROGRAM.C
I tired the solution posted by geek ANCIENT DRAGON. It is not working too....:
c Syntax (Toggle Plain Text)
#include<errno.h> #include<stdio.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; } #include <stdio.h> extern int getline(char [], int); main() { char line[256]; printf("Your names"); getline(line,256); //while(getline(line, 256) != '\0') // printf("you typed \"%s\"\n", line); return 0; }
I tired the solution posted by geek ANCIENT DRAGON. It is not working too....:
c Syntax (Toggle Plain Text)
char line[100]; fgets(line,sizeof(line),stdin);
You have to let it all go Neo! Fear, Doubt, Disbelief!
•
•
Join Date: May 2007
Posts: 12
Reputation:
Solved Threads: 0
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.
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!
•
•
•
•
Here is the SAMPLE.C where gets() works absolutely fine. I dont understand why it isnt working in PROGRAM.C
c Syntax (Toggle Plain Text)
#include<errno.h> #include<stdio.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; } #include <stdio.h> extern int getline(char [], int); main() { char line[256]; printf("Your names"); getline(line,256); //while(getline(line, 256) != '\0') // printf("you typed \"%s\"\n", line); return 0; }
I tired the solution posted by geek ANCIENT DRAGON. It is not working too....:
c Syntax (Toggle Plain Text)
char line[100]; fgets(line,sizeof(line),stdin);
C Syntax (Toggle Plain Text)
#include <stdio.h> int *getline( char *string, size_t size ) { size_t i = 0; for(;;) { int ch = fgetc(stdin); if(ch == '\n' || ch == EOF) { break; } if(i < size - 1) { string[i++] = ch; } } /* forever loop end */ string[i] = '\0'; return string; }
![]() |
Similar Threads
- simple c++ program (any help would be greatly appreciated) (C++)
- Assistance with change program (C++)
- I need a program for fixing errors and stuff... (Legacy and Other Languages)
- Running My Program (C++)
- Deitel's "C++ How To Program" exercise 2.18 (C++)
- WinXP installation program (Windows NT / 2000 / XP)
- Need to Log Program Usage (Windows NT / 2000 / XP)
- Default program to open *.pdf (Mac Software)
Other Threads in the C Forum
- Previous Thread: WinApi GUI Menu Problem
- Next Thread: search binary tree
| Thread Tools | Search this Thread |
#include * adobe ansi array arrays asterisks binarysearch centimeter changingto char character cm convert copyimagefile cprogramme creafecopyofanytypeoffileinc createprocess() database dynamic execv feet fgets file floatingpointvalidation fork function getlogicaldrivestrin givemetehcodez global grade gtkwinlinux hacking histogram inches include incrementoperators infiniteloop input interest intmain() iso kernel keyboard kilometer km license linked linkedlist linux locate looping lowest matrix meter microsoft number oddnumber open opendocumentformat openwebfoundation owf pattern pdf performance pointer posix power probleminc process program programming radix recursion recv recvblocked research reversing segmentationfault sequential single socket socketprograming socketprogramming standard strchr string suggestions systemcall test threads turboc unix urboc user variable voidmain() wab whythiscodecausesegmentationfault windowsapi






