Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Linked Lists and type justification

linked list

  • Please log in to reply
5 replies to this topic

#1 rutwvu

rutwvu

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 23 October 2011 - 10:21 AM

I am currently working on a project where we must read in a file and then print it back out type justified. There must also be a specific number of characters per line based upon user Input with the extra characters being distrubuted spaces. I am reading in each character from the file storing them individually in an array and then placing the whole word into the linked list(I believe). I am not very experienced with C/C++ so I am not sure I am doing this correctly. I have printed the strings which I believe are being fed into the list and mostly they print as expected but occasionally there is random stuff at the end of the word aka diamond becomes diamondssjkd with the extras being random characters. I am looking for any help i can with printing and storing into the linked list... Here is my code.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct listNode {  /* self-referential structure */
   char *data;
   struct listNode *nextPtr;
};

typedef struct listNode LISTNODE;
typedef LISTNODE *LISTNODEPTR;

void readfile();
void insert(LISTNODEPTR *,char *);
void deleteList(int count, char *);
void printList(LISTNODEPTR,int c);
int isChar(char);

main()
{
    int charPerLine = 0;
    readfile();
    printf("How many characters between 55 and 80 per line? \n");
    scanf("%d", &charPerLine);
    while(charPerLine > 80 || charPerLine < 55){
        printf("The character you entered was not in the specified range try again.\n");
        printf("How many characters between 55 and 80 per line? \n");
        scanf("%d", &charPerLine);
    }
    //printList(sPtr,charPerLine);
}

void readfile(){
    FILE *fptr;
    LISTNODEPTR sPtr = NULL;
    int charPerLine = 0;
    char file_name[20];
    int count = 0;
    char c;
    char d;
    char word[50];

    printf("Type in the name of your file followed by .txt. \n");
    scanf("%s",file_name);

    if((fptr = fopen(file_name, "r")) == NULL)
    {
    printf("The file can not be found or does not exist.\n");
    exit(0);
    }//end if


    c = fgetc(fptr);

    while (c != EOF) {

        d = fgetc(fptr);

            /* if two new lines in a row */
            if ((c == '\n') && (d == '\n')) {

                word[count] = '\n';
                count++;
                word[count] = '\n';

                char *newword = malloc(sizeof(LISTNODE));
                newword = word;
                insert(&sPtr,newword);
                deleteList(count, word);

                c = d;
                count = 0;

            }
            /* if not two non-characters in a row */
            else if ((isChar(c) == 0) && (isChar(d) == 0)) {
                c = d;
            }
            /* if c and d are both characters */
            else if ((isChar(c) == 1) && (isChar(d) == 1)) {
                word[count] = c;
                c = d;
                count++;
            }
            /* if c is character and d is space, return, tab, or new line */
            else if ((isChar(c) == 1) && (isChar(d) == 0)) {
                word[count] = c;

                char *newword = malloc(sizeof(LISTNODE));
                newword = word;
                insert(&sPtr, newword);
                deleteList(count, word);

                c = d;
                count = 0;
            }
            /* if d is start of new word */
            else if ((isChar(d) == 1) && (isChar(c) == 0)) {
                c = d;
            }

    }//end while

    fclose(fptr);
}//end readfile


int isChar(char c) {
    if ((c >= 33) && (c <= 126)) {
        return 1;
    }
    return 0;
}

/* insert into list */
void insert(LISTNODEPTR *sPtr, char *value)
{
   LISTNODEPTR newPtr, previousPtr, currentPtr;

   newPtr = malloc(sizeof(LISTNODE));
   printf("%s\n", value);


   if (newPtr != NULL) {    /* is space available */
         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("%c not inserted. No memory available.\n", value);
}

void deleteList(int count, char *word){
    int i = 0;
    for(i = 0; i < count; i++){
    word[i] = (int) NULL;
    }

}//end delete

/* Print the list */
void printList(LISTNODEPTR currentPtr, int numchar)
{
    if (currentPtr == NULL)
      printf("List is empty.\n\n");
    else {
      printf("The list is:\n");

      while (currentPtr != NULL) {
         printf("%s --> ", currentPtr->data);
         currentPtr = currentPtr->nextPtr;
      }

      printf("NULL\n\n");
   }

}

Edited by WingedPanther, 23 October 2011 - 01:20 PM.
add code tags (the # button)

  • 0

#2 WingedPanther73

WingedPanther73

    A spammer's worst nightmare

  • Moderator
  • 17757 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others

Posted 23 October 2011 - 01:22 PM

The first question is: are you doing C or C++? They are not the same, and any response will have to take that into consideration.
  • 0

Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

My MineCraft server site: http://banishedwings.enjin.com/


#3 Ancient Dragon

Ancient Dragon

    CC Addict

  • Senior Member
  • PipPipPipPipPip
  • 378 posts

Posted 23 October 2011 - 04:25 PM

               char *newword = malloc(sizeof(LISTNODE));
                newword = word;

That has three problems:
1. The second line is destroying the memory allocated by the first line -- memory leak

2. The second line doesn't work at all. All its doing is assigning the address of word to neword.

3. word needs to be null-terminated, e.g. word[count] = 0;
Since newword is of type LISTNODE it makes no sence to assign char* to it. What you probably mean is neword->data = word;
  • 0
Visit Grandpa's Forums, a social networking forum, with family-oriented arcade games, blogs, discussion forums, and photo albums.

#4 rutwvu

rutwvu

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 24 October 2011 - 08:39 AM

I ended up trying a different method with reading line per line and printing which solved my general problem although now for certain files when I try insert->nextPtr = malloc(sizeof(LISTNODEPTR)); in my second while loop during read file it error terminates during the run for some files but not all. Here is my new code. Any ideas?

struct listNode{
char *word;
struct listNode *nextPtr;
};

typedef struct listNode LISTNODE;
typedef LISTNODE *LISTNODEPTR;

LISTNODEPTR list = NULL;
LISTNODEPTR insert = NULL;
LISTNODEPTR printPtr = NULL;

void readFile(FILE* filePtr);
void printList(int charPerLine);

main(){
    FILE* openFilePtr = NULL;
    char file_name[20];
    int charPerLine;

    printf("Please specify the file to be read.\n");
    scanf("%s",file_name);
    while((openFilePtr = fopen(file_name, "r")) == NULL)
    {
    printf("The file can not be found or does not exist.\n");
    printf("Please enter the file to be read followed by txt.");
    scanf("%s",file_name);
    }//end if

    printf("How many characters between 55 and 80 per line? \n");
	scanf("%d", &charPerLine);
	while(charPerLine > 80 || charPerLine < 55){
	    printf("The character you entered was not in the specified range try again.\n");
        printf("How many characters between 55 and 80 per line? \n");
        scanf("%d", &charPerLine);
	}//end while


	readFile(openFilePtr);
	printList(charPerLine);


}//end main

void readFile(FILE* fPtr){
    char fileString[256];
    char *wordString = malloc(30*sizeof(char));

    list = malloc(sizeof(LISTNODEPTR));
    fscanf(fPtr, "%s", wordString);
    list->word = malloc(sizeof(wordString));
    strcpy(list->word, wordString);
    list->nextPtr = NULL;
    insert = list;

    while((fgets(fileString, 256, fPtr)) != NULL){
        wordString = strtok(fileString, " ");
        while(wordString != NULL){
            insert->nextPtr = malloc(sizeof(LISTNODEPTR));
            insert = insert->nextPtr;
            insert->word = malloc(sizeof(wordString) + 1);
            strcpy(insert->word, wordString);
            insert->nextPtr = NULL;
            wordString = strtok(NULL, " ");
        }//end while

    }//end while
    fclose(fPtr);

}//end readFile


void printList(int numchar)
{
    printPtr = list;
    int lineLength = 0;

    while(printPtr->nextPtr != NULL)
    {
        lineLength = lineLength + (strlen(printPtr->word)+1);
        if(lineLength >= numchar)
        {
            printf("\n");
            lineLength=0;
        }

        printf("%s ", printPtr->word);
        printPtr = printPtr->nextPtr;
    }
    printf("%s ", printPtr->word);
}

Edited by Alyn, 24 October 2011 - 03:32 PM.
added code tag

  • 0

#5 fread

fread

    Programming God

  • Senior Member
  • PipPipPipPipPipPip
  • 897 posts
  • Location:Trinidad and Tobago
  • Learning:C, Java, C++, C#, PHP, Python, PL/SQL

Posted 24 October 2011 - 09:26 AM

good call @Ancient Dragon.

---------- Post added at 01:26 PM ---------- Previous post was at 12:57 PM ----------

im not sure if this is legal
insert->nextPtr = malloc(sizeof(LISTNODEPTR));

  • 0

#6 Ancient Dragon

Ancient Dragon

    CC Addict

  • Senior Member
  • PipPipPipPipPip
  • 378 posts

Posted 24 October 2011 - 10:38 AM

>>list->word = malloc(sizeof(wordString));
>>insert->word = malloc(sizeof(wordString) + 1);
All the sizeof operator will give you is the size of char* because you are passing it a char*. You can not use sizeof to get the length the string. What you want is list->word = malloc(strlen(wordString)+1);

>>wordString = strtok(NULL, " ");
Huh?? Why are you calling strtok() here?

>>im not sure if this is legal
Yes it is legal.
  • 0
Visit Grandpa's Forums, a social networking forum, with family-oriented arcade games, blogs, discussion forums, and photo albums.





Also tagged with one or more of these keywords: linked list

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download