The problem is to read a paragraph (or more) from an input file, and justify the
ID: 3631464 • Letter: T
Question
The problem is to read a paragraph (or more) from an input file, and justify the text to a user-specified number of characters per row. No words can be hyphenated. It must start by reading the entire file into a linked list of character arrays for all the words in the input file. My problem is when printing my linked list after I have inserted all of the words. I think it's a simple pointer problem, but I can't figure out how to fix it.
#include <stdio.h>
#include <stdlib.h>
struct listNode { /* self-referential structure */
char *data;
struct listNode *nextPtr;
};
typedef struct listNode LISTNODE;
typedef LISTNODE *LISTNODEPTR;
void insert(LISTNODEPTR *, char *);
char delete(LISTNODEPTR *, char *);
int isEmpty(LISTNODEPTR);
void printList(LISTNODEPTR);
void read(char *);
main()
{
int length;
char filename[20];
printf("Enter the name of the file: ");
scanf("%s", filename);
printf("Enter the number of characters per row ");
scanf("%d", &length);
read(filename);
return 0;
}
void read(char *filename)
{
FILE *fptr;
LISTNODEPTR startPtr = NULL;
char word[20];
int size = 0;
fptr=fopen(filename, "r");
while(!feof(fptr)){
fscanf(fptr, "%s", word);
printf("Word: %s ", word);
insert(&startPtr, word);
printList(startPtr);
}
fclose(fptr);
}
/* Insert a new value into the list in sorted order */
void insert(LISTNODEPTR *sPtr, char *value)
{
LISTNODEPTR newPtr, previousPtr, currentPtr;
newPtr = malloc(sizeof(LISTNODE));
if (newPtr != NULL) { /* is space available */
newPtr->data = malloc(sizeof(value));
newPtr->data = value;
newPtr->nextPtr = NULL;
previousPtr = NULL;
currentPtr = *sPtr;
while (currentPtr != NULL) {
previousPtr = currentPtr; /* walk to ... */
currentPtr = currentPtr->nextPtr; /* ... next node */
}
if (previousPtr == NULL) {
newPtr->nextPtr = *sPtr;
*sPtr = newPtr;
}
else {
previousPtr->nextPtr = newPtr;
newPtr->nextPtr = currentPtr;
}
}
else
printf("%s not inserted. No memory available. ", value);
}
/* Print the list */
void printList(LISTNODEPTR currentPtr)
{
if (currentPtr == NULL)
printf("List is empty. ");
else {
printf("The list is: ");
while (currentPtr != NULL) {
printf("%s --> ", currentPtr->data);
currentPtr = currentPtr->nextPtr;
}
printf("NULL ");
}
}
When the program reads in a word, adds it to the list, and prints the list, the output looks like this:
Hello
I'm -> I'm
John -> John -> John
Smith -> Smith -> Smith -> Smith
Any ideas?
Explanation / Answer
is use of linked list compulsory?
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.