Add more than one patient C Pointers - c

I'm having trouble with my pointers. I'm trying to add multiple patients to my list. I know how to do it, it's just that the code gives me seg faults.
Here is the code in question:
void addPatient(int patientID) {
Chartptr patients_chart;
patients_chart = getChart(patientID);
// if patient wasn't found, add new patient
if (patients_chart == NULL) {
Chartptr new_chart;
// allocate and initialize new patient
new_chart = (Chartptr)malloc(sizeof(Chart));
new_chart->id = patientID;
new_chart->buffer = NULL;
// insert new patient into list
new_chart->next = patientList;
patientList = new_chart;
// test print patient data
printf("%d %d\n", new_chart->id, patientList->id);
}
}
/*
* getChart: given a patientID, return a pointer to their Chart
*/
Chartptr getChart(int patientID) {
Chartptr foundChart = NULL;
// find the patient chart with id
foundChart = patientList;
if (foundChart != NULL) {
while(foundChart->id != patientID) {
foundChart = foundChart->next;
}
}
return foundChart;
}
Here are the structs:
/*
* Patient's health chart: ID + linked list of health type readings
*/
typedef struct chartEntry* Chartptr; /* pointer to a Chart */
typedef struct chartEntry{
int id; /* patient ID */
CBuffptr buffer; /* pointer to first health type buffer */
Chartptr next; /* pointer to next patient */
}Chart;
extern Chartptr patientList; /* global declaration for start of the patient chart linked list */
I'm sending to the add patient, id, which I get from main, that much I know works perfectly.
But for some reason when the patientList is not NULL and it enters the while loop it seg faults or its after the while loop in the rest of addPatient. I don't know which. Thanks for your help.

I think here is your error:
while(foundChart->id != patientID) {
foundChart = foundChart->next;
You are updating foundChart but never checking in the while loop if it had become NULL, in case no patientID matches.

getChart() has no condition stop it running off the end of the list if no match is found.

Please update code as given below it will work :D
Chartptr getChart(int patientID) {
Chartptr foundChart = NULL;
// find the patient chart with id
foundChart = patientList;
while(foundChart!= NULL) {
if(foundChart->id == patientID) {
return foundChart;
}
foundChart = foundChart->next;
}
return NULL;
}

Related

My program is throwing an exception trying to delete an element from a linked list

I have a linked list and two functions - one to add and other to delete members from the list.
When I try to delete a member I am getting an exception in the delete function.
The exception is in line
if (strcmp((temp_person_ptr->name), name_to_remove))
The exception says -> Unhandled exception at 0x50C4EF18 (ucrtbased.dll) in singly_linked_list.exe: 0xC0000005: Access violation reading location 0xDDDDDDDD. occurred
Full program is below -
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
#include "globals.h"
extern struct person* starting_address;
struct person* delete_person(size_t* list_size_ptr, struct person* ptr_current_person)
{
printf("There are %u items in list \n", *list_size_ptr);
struct person* temp_person_ptr = starting_address, *to_save_person_ptr;
printf("The items in list are \n");
while (temp_person_ptr)
{
printf("%s \n", temp_person_ptr->name);
temp_person_ptr = temp_person_ptr->next_person_ptr;
}
char name_to_remove[MAX_NAME_LENGTH];
printf("Please enter the name to remove \n");
gets_s(name_to_remove, MAX_NAME_LENGTH - 1);
temp_person_ptr = starting_address;
to_save_person_ptr = starting_address; // Not required by logic - just to initialize for compiler
while (temp_person_ptr)
{
if (strcmp((temp_person_ptr->name), name_to_remove))
{
to_save_person_ptr = temp_person_ptr;
temp_person_ptr = temp_person_ptr->next_person_ptr;
}
else
{
// Since we are going to remove temp_person_ptr - we save it's next person_ptr in preceding person which is to_save_person_ptr
// Only if the person_ptr to be removed is NOT the first person
// For now - assume - one element name will match
if (temp_person_ptr != starting_address)
to_save_person_ptr->next_person_ptr = temp_person_ptr->next_person_ptr; // takes care if temp_person_ptr is the last one as well
else // Else the next person's address is the new starting address
starting_address = temp_person_ptr->next_person_ptr;
free(temp_person_ptr);
(*list_size_ptr)--;
}
}
return (ptr_current_person);
}
The part to add an element to the list looks as below (entire function) -
struct person* add_person(size_t* list_size_ptr, struct person* ptr_current_person)
{
struct person *ptr_new_person;
ptr_new_person = (struct person*) malloc(sizeof(struct person));
// If first person- its starting address is the starting address of list
if ((*list_size_ptr) == 0)
{
starting_address = ptr_new_person;
}
else
{
//1. Add the new address to the chain - only if this is not the first person
ptr_current_person->next_person_ptr = ptr_new_person;
}
ptr_new_person->next_person_ptr = NULL;
printf("Please enter the name \n");
gets_s(ptr_new_person->name, MAX_NAME_LENGTH - 1);
// 2. We may make ptr_new_person as ptr_current_person
ptr_current_person = ptr_new_person;
// 3. Now onwards ptr_current_person refers to the pointer to the newly added person
(*list_size_ptr)++;
return (ptr_current_person);
}
while (temp_person_ptr)
{
if (strcmp((temp_person_ptr->name), name_to_remove))
{
to_save_person_ptr = temp_person_ptr;
temp_person_ptr = temp_person_ptr->next_person_ptr;
}
else{...}
From this snippet it looks like temp_person_ptr is pointing to something, but the ->name is NULL. Add a printf statement like this before your strcmp:
if(!(temp_person_ptr->name)){
printf("This is why your segfaulting\n");
}
And you will either see that ->name is null or its something else. good luck
You haven't posted enough to get a proper analysis and help. The guidance for making a complete, minimal example isn't just for grins; often by reducing a problem to its core, the programmer finds their error themselves. If not, it gives a great place for other to. Regardless, the loop in your delete is essentially:
temp = start;
while (temp) {
if (strcmp(temp->name, name)) {
temp = temp->next;
} else {
free(temp);
}
}
Your free should likely have been something like:
void *p = temp->next;
free(temp);
temp = p;
It worked, I was not exiting the while loop after free and going on all the way.
I added a return to return after free is done and list size is decremented. It works now.

Doubly Linked List C, insertion at specific position

I could really use some help with an address book program I've been struggling on for days now. I'm working with a doubly linked list in C. I'm trying to add nodes into the list at user-entered positions, starting with position 0. The positions will not be entered out of range. (no inserts at position 1 before something at position 0 etc.) The positions can be repeated though: inserting the new node in the position before the previous position occupant. (for example: if position 1 has x, and new node is inserted at position 1 with y, position 1 now has y and position 2 has x)
I need to take the user entered position number and retrieve the current person in that position, but I can't quite get it right. Also, I have included my insert function if you wanted to take a look at that as well because it isn't working properly either. Thanks for any help!
EDIT: The main problem right now is that my code for finding pPersonCur is failing when position == 1. Also, the insert function is not entering things in the proper order (the newest insertion in a position does not displace the older insertion correctly). The broken pPersonCur code makes it hard to diagnose why exactly this is, however.
addressbook.h excerpt:
typedef struct person Person;
struct person {
char lastName[255];
char firstName[255];
char email[255];
char phoneNumber[255];
Person *pNext;
Person *pPrev;
};
addressbook.c excerpt:
#include "addressbook.h"
Person * InsertPerson(Person * pPersonCur) {
Person * pPersonNew;
/* data gathered for CreatePerson() function here */
pPersonNew = CreatePerson(pLastName, pFirstName, pEmail, pPhoneNumber);
if (pPersonCur)
{
pPersonNew->pNext = pPersonCur;
pPersonNew->pPrev = pPersonCur->pPrev;
pPersonCur->pPrev = pPersonNew;
if (pPersonNew->pPrev)
pPersonNew->pPrev->pNext = pPersonNew;
} else
{
pPersonNew->pPrev = pFirst;
pPersonNew->pNext = NULL;
if (pFirst)
pFirst->pNext = pPersonNew;
}
return (pPersonNew);
}
main.c excerpt:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "addressbook.h"
Person *pFirst; /* First name in list */
int main(void) {
Person *pPersonCur = NULL; /* current Person */
int bDone = 0, position = 0, counter = 0;
pFirst = NULL;
printf("Ready\n");
while (!bDone) {
char input = getchar();
switch (input) {
case 'a':
counter = 0;
scanf("%d", &position); /* Where desired position is entered */
if (position == 0) {
if (pFirst) {
if (pFirst->pNext) {
pPersonCur = pFirst->pNext;
}
} else {
pPersonCur = pFirst;
}
} else {
pPersonCur = pFirst->pNext;
while (counter < position) {
pPersonCur = pPersonCur->pNext;
counter++;
}
}
InsertPerson(pPersonCur); /* Takes in person at desired position, return value is new inserted person */
break;
/* Some other cases here */
case 'q':
bDone = 1;
break;
}
}
/* Rest of code */
It seems so that you never assign a value to pFirst.
When position is not 0 the line pPersonCur = pFirst->pNext; is executed and pFirst in this place is still NULL.
Add a condition to your insert function to check whether list's head is assigned.
Person * InsertPerson(Person * pPersonCur) {
. . .
else
{
pPersonNew->pPrev = pFirst;
pPersonNew->pNext = NULL;
if (pFirst)
pFirst->pNext = pPersonNew;
else
pFirst = pPersonNew; // If pFirst is not assigned, assign it to newly created person
}
return (pPersonNew);
}
Despite that, if you happen to call InsertPerson with NULL argument, your code would put new Person after the first one and cut the rest of the list off.
To put new Person to the end of the list when called with NULL you could use something like this in your InsertPerson function:
if(pFirst) {
Person *last = pFirst;
while(last->pNext != NULL) {
last = last->pNext;
}
last->pNext = pPersonNew;
pPersonNew->pPrev = last;
}
else
pFirst = pPersonNew;
Insertion according to position index might fail as well if you give a position index that is higher than there are nodes in the list. Some sort of safety check should be added as well.
pPersonCur = pFirst->pNext;
while (counter < position && pPersonCur->pNext != NULL) { // If last node reached, stop the loop
pPersonCur = pPersonCur->pNext;
counter++;
}
This implementation would add new Person to the end of the list if position index is too high.

void function with return terminator

If I want to end the compiling of a void function, do I break or return NULL?
This is a piece of code that returns an error.
void addUser( const char *name ) {
//create Usernode and void *data (user w/ friends)
//check to see if User already exists
if ( findUser(name) != NULL) {
return;
}
//create data for node
User *registeredData = malloc(sizeof(struct User_struct)); //first user Data
registeredData->name = name;
//create a Friends
//put this in file create Friends
Friends initAmigos;
initAmigos = (Friends)malloc(sizeof(struct Friends_struct)); //NOTE: NO POINTERS HERE
//set Friends list to Null
initAmigos->amigos_Queue = que_create( NULL );
registeredData->amigos = initAmigos;
//void que_insert( QueueADT queue, void *data )
que_insert( initAmigo , registeredData);
printf("%s User was inerted \n", name);
}
You can "return;" from a void function, which stops execution execution of the function, and returns to the calling code.
You said "stop compiling", which shows a misunderstand of the difference between execution and compiling. Compiling+linking converts your code (in its entirety) into something that can be executed on a processor. Functions are then "run" on that processor until they complete. A void function can signal that its complete by having a return statement that has no value.

C Pointers Segmentation Fault

I'm having this strange segmentation fault. I'm trying to find if a patients id already exists in the list of patients using pointers. I think the code in question is:
#include <stdio.h>
#include <stdlib.h>
#include "health.h"
void addPatient(int patientID) {
printf("here1");
Chart* patients_chart;
// find the patient with id
patients_chart = patientList;
while(patients_chart == NULL || patients_chart->id == patientID) {
patients_chart = patients_chart->next;
printf("here2");
}
printf("here3");
// if patient wasn't found, add new patient
if (patients_chart == NULL) {
Chart *new_chart;
printf("here4");
// allocate and initialize new patient
new_chart = (Chart*)malloc(sizeof(Chart));
new_chart->id = patientID;
new_chart->buffer = NULL;
// insert new patient into list
new_chart->next = patientList;
patientList = new_chart;
printf("here5");
}
}
The included health.h is just method declarations and structs. I will list them below, but please note that my assignment restricts me from modifying any of the code in health.h. I will also post my code at the very end.
/*
* Patient's health chart: ID + linked list of health type readings
*/
typedef struct chartEntry* Chartptr; /* pointer to a Chart */
typedef struct chartEntry{
int id; /* patient ID */
CBuffptr buffer; /* pointer to first health type buffer */
Chartptr next; /* pointer to next patient */
}Chart;
extern Chartptr patientList;
I call the function in main with input like this one: 1,12:12:12,7,0
The 7 is the "command"
the 1 is the patient id in question
You can ignore the rest.
I understand how to find the patient, but I'm getting this annoying seg fault. Thank you for your time!
The following code is buggy:
while(patients_chart == NULL || patients_chart->id == patientID) {
patients_chart = patients_chart->next;
printf("here2");
}
You are advancing for as long as either the pointer is NULL or the pointer matches the patient ID. You're missing a negation there. Instead, use:
while(patients_chart != NULL && patients_chart->id != patientID) {
patients_chart = patients_chart->next;
printf("here2");
}
while(patients_chart == NULL || patients_chart->id == patientID) {
patients_chart = patients_chart->next;
}
Here if Condition 1 (patients_chart == NULL) is true, then you do this:
patients_chart = patients_chart->next;
which is Null Pointer Dereferencing, thus causing Seg Fault.

Sending "cls" to dos causes exception

Due to a problem posting, my last question (duplicate of this) was closed.
Background is provided at the end so you can get straight to the problem.
I have a text-based program to help learn vocabulary or anything else (basically simulates flash cards, but flashes up the ones you don't know more often). It seemed to work fine while I was testing it, until I got fed up of the constant backlog of text on the screen, so I implemented a (somewhat unportable) clear screen routine.
Then it started throwing up exceptions, and I put in all sorts of debugging code to try and track it down.
Well... I managed to narrow it down to the following command on line 445:
system("cls");
How can this command cause an exception? Does anyone know a workaround?
I've run this in command prompts on both Windows Vista and Windows 7 with the same result.
Complete source in case anyone wants to compile it themselves or take a look through:
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <process.h>
#include <ctype.h>
#include <string.h>
#define DINPUTFILENAME "vtdb.~sv"
#define DOUTPUTFILENAME "vtdb.~sv"
#define MAXINTVALUE 2147483647
#define MAXTEXTLENGTH 256
#define N2LTONORM 5
#define NORMTON2L 3
#define NORMTOKNOWN 5
#define KNOWNTONORM 2
#define KNOWNTOOLD 2
#define OLDTONORM 1
struct vocab
{
int index; //identifies the entry in the list, allowing it to be selected by use of a random number
char * question;//pointer to question text
char * answer;//pointer to the answer text, which is required for the response to be considered correct
char * info;//pointer to optional extra text giving advice such as to how to format the response
char * hint;//pointer to optional text giving a clue to the answer
int right;//indicates whether counter is counting correct or incorrect responses
int counter;//counts how many times in a row the answer has been correct/incorrect
int known;//indicates to what level the vocab is known, and thus to which list it belongs (when loading/saving)
struct vocab * next;//pointer to next in list
};
struct listinfo//struct holds head, tail and the number of entries for the n2l, norm, known and old lists
{
struct vocab * head;
int entries;
struct vocab * tail;
};
struct listinfo n2l, norm, known, old;
int n2l_flag; //Prevents 'need to learn's coming up twice in a row
int maxtextlength = MAXTEXTLENGTH; //allows use of this #define within text strings
FILE * inputfile;
FILE * outputfile;
void getrecordsfromfile(char * inputfilename,char separator);//load
char * readtextfromfile(int maxchars,char separator);//get text field from file
int readnumberfromfile(int maxvalue,char separator);//get integer field from file
struct vocab * addtolist(struct vocab * newentry, struct listinfo * list);//add given (already filled in) vocab record to given list
int removefromlist(struct vocab * entry, struct listinfo * list,int freeup);//remove given entry from given list. Also destroy record if freeup is true
void reindex (struct listinfo * list);//necessary to stop gaps in the numbering system, which could cause random vocab selection to fail
int writeliststofile();//save
void testme();//main code for learning vocab, including options menu
char * gettextfromkeyboard(char * target,int maxchars);//set given string (char pointer) from keyboard, allocating memory if necessary
int getyesorno();//asks for yes or no, returns true (1) if yes
void testrandom();//code keeps causing exceptions, and as it's so random, I'm guessing it's to do with the random numbers
void getrecordsfromfile(char * inputfilename,char separator)
{
int counter = 0;
struct vocab * newvocab;
struct listinfo * newvocablist;
if (!(inputfile = fopen(inputfilename, "r")))
{
printf("Unable to read input file. File does not exist or is in use.\n");
}
else
{
printf("Opened input file %s, reading contents...\n",inputfilename);
while (!feof(inputfile))
{
newvocab = (struct vocab *)malloc(sizeof(struct vocab));
if (!newvocab)
{
printf("Memory allocation failed!\n");
return;
}
else
{
newvocab->question=readtextfromfile(MAXTEXTLENGTH,separator);
newvocab->answer=readtextfromfile(MAXTEXTLENGTH,separator);
newvocab->info=readtextfromfile(MAXTEXTLENGTH,separator);
newvocab->hint=readtextfromfile(MAXTEXTLENGTH,separator);
newvocab->right=readnumberfromfile(1,separator);
newvocab->counter=readnumberfromfile(0,separator);
newvocab->known=readnumberfromfile(3,separator);
switch (newvocab->known)
{
case 0: newvocablist = &n2l;break;
case 1: newvocablist = &norm;break;
case 2: newvocablist = &known;break;
case 3: newvocablist = &old;break;
}
addtolist(newvocab,newvocablist);
if (newvocab->question==NULL||newvocab->answer==NULL)
{
printf("Removing empty vocab record created from faulty input file...\n");
removefromlist(newvocab,newvocablist,1);
}
else counter++;
}
}
fclose(inputfile);
printf("...finished.\n%i entries read from %s.\n\n",counter,inputfilename);
}
return;
}
char * readtextfromfile(int maxchars,char separator)
{
int i=0;
char ch;
char * target = (char *)malloc(maxchars+1); //allocate memory for new string
if (!target) {printf("Memory allocation failed!\n");return 0;}//return 0 and print error if alloc failed
ch=getc(inputfile);
if (ch==separator){free(target);return NULL;}//if field is blank (zero-length), return null pointer
while (isspace(ch))
{
ch = getc(inputfile);//cycle forward until you reach text
if (ch == separator||ch=='\n'||ch==EOF) {free(target);return NULL;}//if no text found(reached ~ before anything else), return null pointer
}
if (ch=='"') //Entry is in quotes (generated by excel when exporting to .csv and field contains a comma)
{
ch=getc(inputfile);//move to next character after the quotes
while (i<maxchars && ch!='"' && ch!='\n')//stop when you reach the end quotes, end of line, or when text too long
{
target[i++]=ch;
ch = getc(inputfile); //copy name from file to target, one char at a time
}
}
else //entry is not in quotes, so char is currently first letter of string
{
while (i<maxchars && ch!=separator && ch!='\n')//stop when you reach separator, end of line, or when text too long
{
target[i++]=ch;
ch = getc(inputfile); //copy name from file to target, one char at a time
}
}
target[i] = '\0';//terminate string
return target;
}
int readnumberfromfile (int maxvalue,char separator)
{
int number, i=0;
char ch;
char * buff = (char *)malloc(11);
if (!buff) {printf("Memory allocation failed!\n");return 0;}//return 0 and print error if alloc failed
if (!maxvalue) maxvalue=MAXINTVALUE;
ch=getc(inputfile);
while (!isdigit(ch))
{
ch = getc(inputfile);//cycle forward until you reach a digit
if (ch == separator||ch=='\n'||ch==EOF) {printf("Format error in file\n");return 0;}//if no number found(reached ~ before digit), print error and return 0
}
while (i<11 && ch!=separator && ch!='\n')//stop when you reach '~', end of line, or when number too long
{
buff[i++]=ch;
ch = getc(inputfile); //copy number from file to buff, one char at a time
}
buff[i] = '\0';//terminate string
number = atoi(buff)<=maxvalue ? atoi(buff) : maxvalue;//convert string to number and make sure it's in range
free(buff);
return number;
}
struct vocab * addtolist(struct vocab * newentry, struct listinfo * list)
{
if (!list->head)//if head is null, there is no list, so create one
{
list->head = list->tail = newentry;//this is the new head and tail
list->entries = newentry->index = 1;
newentry->next = NULL;// FISH! not sure if this is necessary, but just be sure...
}
else//just appending to the list
{
list->tail->next = newentry;//adjust current tail to point to new entry
list->tail = newentry;//make the new entry the new tail
newentry->index=++list->entries;
newentry->next = NULL;
}
return newentry;
}
int removefromlist(struct vocab * entry, struct listinfo * list,int freeup)
{
struct vocab * prev;
if (list->head == entry) //if entry being deleted is first in the list
{
if (list->tail == entry) //if entry is only item in the list
{
list->head = list->tail = NULL;
}
else //if first in list, but not last
{
list->head = entry->next;
}
}
else //entry is not first in list, so set prev to point to previous entry
{
prev = list->head;
while (prev->next!=entry)
{
prev=prev->next;
if (!prev)
{
printf("Trying to delete an entry from a list it's not in!!\n");
return 0;
}
}
if (list->tail == entry)//if entry is at the end of the list
{
list->tail = prev;
list->tail->next = NULL;
}
else //if entry is somewhere in middle of list
{
prev->next=entry->next;
}
}//this entry is now not pointed to in any list
list->entries--;
/*following line removed because it could theoretically break a list if the entry was removed from a list after it had been added to another
entry->next = NULL;//and doesn't point to anything either*/
reindex(list);
if (freeup) //if freeup is set, this also wipes the record and frees up the memory associated with it
{
free(entry->question);
free(entry->answer);
free(entry->info);
free(entry->hint);
free(entry);
}
return 1;
}
void reindex (struct listinfo * list)
{
int counter = 1;
struct vocab * workingentry = list->head;
while (workingentry)
{
workingentry->index = counter++;
workingentry=workingentry->next;
}
if (list->entries!=counter-1) printf("Reindexing Error!\n");
}
int writeliststofile()
{
int i,counter=0;
struct listinfo * list;
struct vocab * entry;
if (!(outputfile = fopen(DOUTPUTFILENAME, "w")))
{
printf ("Error accessing output file!\n");
return 0;
}
else
{
printf("Saving...\n");
for (i=0;i<=3;i++)
{
switch (i)
{
case 0: list = &n2l;break;
case 1: list = &norm;break;
case 2: list = &known;break;
case 3: list = &old;break;
default: printf("Loop Error!\n");break;
}
entry=list->head;
while (entry!=NULL)
{
if (counter) fprintf(outputfile,"\n");
fprintf(outputfile,"%s~%s~%s~%s~%i~%i~%i",entry->question,entry->answer,entry->info,entry->hint,entry->right,entry->counter,i);
entry=entry->next;
counter++;
}
}
fclose(outputfile);
printf("...finished. %i entries saved.\n",counter);
return 1;
}
}
void testme()
{
int list_selector, entry_selector, bringupmenu = 0, testagain=1;
char testmenuchoice = '\n';
char * youranswer = (char *)malloc(MAXTEXTLENGTH+1);
struct listinfo * currentlist;
struct vocab * currententry;
if (!youranswer) {printf("Memory allocation error!\n");return;}
while (testagain)
{
fprintf(stderr,"Start of 'testagain' loop\nClearing screen...\n");
system("cls");
//select a list at random, using the percentage probabilities in the if statements. FISH! Can this be done with a switch and ranges?
fprintf(stderr,"Assigning list selector to random value...");
list_selector = (((float)rand() / 32768) * 100)+1;
fprintf(stderr,"assigned list selector value %i\nAssigning list pointer...",list_selector);
if (list_selector<33) currentlist = &n2l;
if (list_selector>32&&list_selector<95) {n2l_flag=0;currentlist=&norm;} //use norm list and cancel n2l flag (not cancelled with other lists)
if (list_selector>94&&list_selector<100) currentlist = &known;
if (list_selector==100) currentlist = &old;
fprintf(stderr,"assigned list pointer %x\nModifying pointer...",currentlist);
//do a little control over random selection
if (currentlist==&n2l && n2l_flag) {currentlist=&norm; n2l_flag=0;} //if n2l list was used last time as well (flag is set), use entry from the norm list instead
if (currentlist==&n2l) n2l_flag = 1; //is using n2l this time, set flag so it won't be used next time as well
if (currentlist->entries==0) currentlist = &norm;//if current list is empty, default to normal list
if (currentlist->entries==0 && !n2l_flag) currentlist = &n2l;//if normal list is empty, try n2l list if it wasn't used last time
if (currentlist->entries==0 && list_selector%10==5) currentlist = &old;//if list is still empty, in 10% of cases try old list
if (currentlist->entries==0) currentlist = &known;//in the other 90% of cases, or if old is empty, use the known list
if (currentlist->entries==0) currentlist = &old;//if known list is empty, try the old list
if (currentlist->entries==0) {currentlist = &n2l;n2l_flag=1;}//if old list is empty, use n2l list EVEN if it was used last time
if (currentlist->entries==0) {printf("No entries in list!");return;} //if list is STILL empty, abort
fprintf(stderr,"modified list pointer\nAssigning entry selector...");
//we now have the desired list of words with at least one entry, let's select an entry at random from this list
entry_selector = (((float)rand() / 32767) * currentlist->entries)+1;
fprintf(stderr,"assigned entry selector value %i\nAssignig pointer...",entry_selector);
currententry = currentlist->head;
fprintf(stderr,"set entry pointer to head, going to loop to it...\n");
while (currententry->index!=entry_selector)
{
currententry = currententry->next;//move through list until index matches the random number
if (currententry==NULL) {printf("Indexing error!\nCurrent list selector: %i, entries: %i, entry selector: %i\n",list_selector,currentlist->entries,entry_selector);return;}//in case not found in list
}
fprintf(stderr,"Looped, testing.\n");
printf("Translate the following:\n\n\t%s\n\n",currententry->question);
if (!currententry->info) printf("There is no additional information for this entry.\n");
else printf("Useful Info: %s\n\n",currententry->info);
printf("Your Translation:\n\n\t");
gettextfromkeyboard(youranswer,MAXTEXTLENGTH);
if (!strcmp(youranswer,currententry->answer))//if you're right
{
printf("Yay!\n");
if(currententry->right) currententry->counter++;
else currententry->right = currententry->counter = 1;
if (currententry->counter>2) printf("You answered correctly the last %i times in a row!\n",currententry->counter);
//make comments based on how well it's known, and move to a higher list if appropriate
if (currentlist==&n2l && currententry->counter>=N2LTONORM)
{
removefromlist(currententry,currentlist,0);
printf("Looks like you know this one a little better now!\nIt will be brought up less frequently.\n");
currententry->counter = 0;
addtolist(currententry,&norm);
}
if (currentlist==&norm && currententry->counter>=NORMTOKNOWN)
{
removefromlist(currententry,currentlist,0);
printf("Looks like you know this one now!\nIt will be brought up much less frequently.\n");
currententry->counter = 0;
addtolist(currententry,&known);
}
if (currentlist==&known && currententry->counter>=KNOWNTOOLD)
{
removefromlist(currententry,currentlist,0);
printf("OK! So this one's well-learnt.\nIt probably won't be brought up much any more.\n");
currententry->counter = 0;
addtolist(currententry,&old);
}
}
else //if you're wrong
{
printf("\nSorry, the correct answer is:\n\n\t%s\n\n",currententry->answer);
if(!currententry->right) currententry->counter++;
else {currententry->right = 0; currententry->counter = 1;}
if (currententry->counter>1) printf("You've got this one wrong the last %i times.\n",currententry->counter);
if (currentlist==&norm && currententry->counter>=NORMTON2L)
{
removefromlist(currententry,currentlist,0);
printf("This one could do with some learning...\n");
currententry->counter = 0;
addtolist(currententry,&n2l);
}
if (currentlist==&known && currententry->counter>=KNOWNTONORM)
{
removefromlist(currententry,currentlist,0);
printf("OK, perhaps you don't know this one as well as you once did...\n");
currententry->counter = 0;
addtolist(currententry,&norm);
}
if (currentlist==&old && currententry->counter>=OLDTONORM)
{
removefromlist(currententry,currentlist,0);
printf("This old one caught you out, huh? It will be brought up a few more times to help you remember it.\n");
currententry->counter = 0;
addtolist(currententry,&norm);
}
}
fprintf(stderr,"Tested, options menu?\n");
printf("Type 'o' for options or strike enter for another question\n");
testmenuchoice = getchar();
fprintf(stderr,"Got choice\n");
if (tolower(testmenuchoice)=='o') bringupmenu = 1;
fprintf(stderr,"set menuflag\n");
if (testmenuchoice!='\n') while (getchar()!='\n')getchar();
fprintf(stderr,"cleared getchar\n");
while (bringupmenu)
{
system("cls");
printf("Current Entry:\n\nQuestion: %s\nAnswer: '%s'\n",currententry->question,currententry->answer);
if (currententry->info) printf("Info: %s\n",currententry->info); else printf("No info.\n");
if (currententry->hint) printf("Hint: %s\n\n",currententry->hint); else printf("No hint.\n\n");
printf("Options Menu:\n\nType q to modify the question phrase displayed for translation.\nType a to change the answer phrase you must provide.\nType i to add/modify additional info for this entry.\nType h to add/modify the hint for this entry.\nType p to mark this entry as high priority to learn.\nType d to delete this entry from the database.\nType x to end testing and return to the main menu.\n\n");
testmenuchoice=getchar();
while (getchar()!='\n') getchar();
switch (testmenuchoice)
{
case 'q': printf("Enter new question text for this entry (max %i chars):\n",maxtextlength);
currententry->question=gettextfromkeyboard(currententry->question,MAXTEXTLENGTH);
break;
case 'a': printf("Enter new answer text for this entry (max %i chars):\n",maxtextlength);
currententry->answer=gettextfromkeyboard(currententry->answer,MAXTEXTLENGTH);
break;
case 'i': printf("Enter new info for this entry (max %i chars):\n",maxtextlength);
currententry->info=gettextfromkeyboard(currententry->info,MAXTEXTLENGTH);
break;
case 'h': printf("Enter new hint for this entry (max %i chars):\n",maxtextlength);
currententry->hint=gettextfromkeyboard(currententry->hint,MAXTEXTLENGTH);
break;
case 'p': if(currentlist=&n2l)printf("Already marked as priority!\n");
else
{
removefromlist(currententry,currentlist,0);
currententry->counter = 0;
currentlist=&n2l;
addtolist(currententry,currentlist);
printf("Entry will be brought up more often\n");
}
break;
case 'd': printf("Are you sure you want to delete this entry?\nOnce you save, this will be permanent!(y/n)");
if (getyesorno()) {removefromlist(currententry,currentlist,1);printf("Entry deleted!\n");bringupmenu=0;}
else printf("Entry was NOT deleted.\n");
break;
case 'x': bringupmenu = testagain = 0;
break;
default: printf("Invalid choice.\n");
}
if (bringupmenu)
{
printf("Select again from the options menu? (y/n)");
bringupmenu = getyesorno();
}
if (!bringupmenu&&testagain)
{
printf("Continue testing? (y/n)");
testagain = getyesorno();
}
}
fprintf(stderr,"End of 'testagain' loop.\n Clearing Screen...");
system("cls");
}
free(youranswer);
// getchar();
return;
}
char * gettextfromkeyboard(char * target,int maxchars)
{
int i =0;
char ch;
if (!target)//if no memory already allocated (pointer is NULL), do it now
{
target=(char *)malloc(maxchars+1);
if (!target) {printf("Memory allocation failed!");return NULL;} //return null if failed
}
ch = getchar();
if (ch=='\n') {free(target);return NULL;}//if zero length, free mem and return null pointer
while (!isalnum(ch))//cycle forward past white space
{
ch=getchar();
if (ch=='\n') {free(target);return NULL;}//if all white space, free mem and return null pointer
}
while (ch!='\n' && i<maxchars)
{
target[i++]=ch;
ch=getchar();
}
target[i]='\0';
return target;
}
int getyesorno()
{
char yesorno = '\n';
while (toupper(yesorno)!='Y'&&toupper(yesorno)!='N')
{
yesorno=getchar();
if (toupper(yesorno)!='Y'&&toupper(yesorno)!='N') printf("Invalid choice. You must enter Y or N:\n");
}
while (getchar()!='\n') getchar();
if (toupper(yesorno)=='Y') return 1;
else return 0;
}
void testrandom()
{
return;
}
int main(int argc, char* argv[])
{
char * inputfilename = DINPUTFILENAME;
char * outputfilename = DOUTPUTFILENAME;
char separator = '~';
char menuchoice = '\0';
n2l.entries = norm.entries = known.entries = old.entries = 0;
srand((unsigned)time(NULL));
fprintf(stderr,"Start...\n");
printf("Loading...\nLoad default database? (y/n)");
if (!getyesorno())
{
printf("Default file type is .~sv. Import .csv file instead? (y/n)");
if (getyesorno())
{
separator = ',';
printf("Enter name of .csv file to import:\n");
}
else
{
printf("Enter name of .~sv file to load:\n");
}
inputfilename = gettextfromkeyboard(inputfilename,256);
}
getrecordsfromfile(inputfilename,separator);
while (menuchoice!='x')
{
printf("Welcome to the Vocab Test, version C!\n\nMain menu:\n\n\tt: Test Me!\n\ts: Save\n\tx: Exit\n\n");
menuchoice = getchar();
while (getchar()!='\n') getchar();
switch (tolower(menuchoice))
{
case 'x': break;
case 't': testme(); break;
case 's': writeliststofile();break;
case 'w': testrandom(); break;
default: printf("Invalid choice. Please try again.\n"); break;
}
system("cls");
}
system("cls");
printf("Bye for now!\n\nPress enter to exit.");
getchar();
fprintf(stderr,"Successfully closed\n");
return 0;
}
I tried adding the output of stderr on a typical run, but it makes the body too long. Also tried adding it as an answer, but:
Users with less than 100 reputation can't answer their own question for 8 hours after asking. You may self-answer in 7 hours. Until then please use comments, or edit your question instead.
Background: I made my first foray into programming earlier this year, and decided I wanted to start with C before moving on to C++, Java, and perhaps Python and C#.
To get me started in C, after the obligatory hello world, I wrote a small game (text based, also including the "cls" command), and then moved onto this little vocab tester, which was to help me learn Indonesian while I was away in Austria speaking German :-D. I eventually got exasperated at the cls crash and haven't programmed since. I really want to pick it back up, so I'm starting here with this question.
Have you tried printing '\f'? That's the "formfeed" character.
EDIT: I've had a closer look at your code, and there's some stuff going on that I don't like. :-)
For example, in gettextfromkeyboard, if you enter only whitespace, it'll free target, even if that was non-NULL on entry.
In this line:
inputfilename = gettextfromkeyboard(inputfilename,256);
it passes inputfilename, which points to a constant string, into gettextfromkeyboard. Trying to free that is a bad idea.
I also have my doubts about while (getchar()!='\n') getchar();.
Suppose the input is "ABC\n".
The condition will consume and return 'A', the body of the loop will consume 'B', the condition will consume and return 'C', and the body of the loop will consume '\n'.
Try one of the many curses, ncurses, etc. packages around. There should be one somewhere on the web for your version of C, if it is not too uncommon. It should handle all kinds of text screen functionality, including clearing the screen and it is pretty portable.
Possibly system('cls') has been deprecated? Here is another way of doing it.
The code runs fine for me and the CLS command works. Non-reproduceable crashes often indicate memory corruption. I'd say a good place to look first is your readtextfromfile function since it will overwrite the input buffer if a file contains 256 chars.

Resources