-1

I have this code that reads in values from a .txt file and returns the strings ending in ed.

It compiles and runs, but I can't figure out why it returns the last word twice. I thought it was the FEOF statement. Any hints or clues?

The program is supposed to prompt the user for the name of a text file (if the file does not exist, display an error message and re-prompt), this works.

Read in a series of strings from the text file and store these in an array of strings, dynamically allocating memory for each element, this works.

Loop through the populated string array and find elements that end with the characters "ed".

Display on-screen a list of only those strings that end with "ed", works but duplicates the last word.

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

#define SIZES_1 20 // preprpcessor directive for size of the filename array
#define SIZES_2 500 // preprocessor directive for size of the word array

// the file name needs to be a constant so that it is not changed 
int readInData (const char *fileName, char* array[] ); // function protype with arguments making pointer to char that is a constant called filename,
                                                        // with pointer to an char array

//  function main
int main(void){
    char fileName[SIZES_1];
    char *array[SIZES_2];

    int i; // loop counter variable
    int length; // length of current string
    int N; //Size of filled array
    int userPrompt=0; // used for signaling if file can be read correctly , default value is set to zero

// while loop to be used to as a signal with userPrompt to keep prompting user fro filename Prompt the user for the name of a text file 
//(if the file does not exist, display an error message and re-prompt)
    while (userPrompt==0){

        puts("Please Input the Text file name (Max 20 characters):   ");
        scanf("%s", fileName);

        if (-1 == (N = readInData(fileName,array))){// perform error check and if non pass to function
            printf("File error try again.\n");
            userPrompt=0; // keeps signal flag at 0
        }
        else
        {
            userPrompt=1;// sets flag to 1 and loop is exited
        }
    }// end of signal while loop
    printf("\n the Following Strings end with ed: \n ");

    // loop through 
    for (i = 0; i <= N; i++){

        length = strlen(&array[i][0]); // strlen is used to f9ind the length of the string, address of array is used after trial error, array is a pointer start at i index 0 

        // compare and 
        if (strcmp(&array[i][length -2], "ed")==0){// compare the value at memory location and if last 2 letters are set return value to  0 then it is equal
            printf("%s\n", &array[i][0]);// print the value at memory location 
        }  
    }

    //free((array)); //deallocate memory from function malloc got error mesages until i used the double brackets
    return 0;
}                                                         

int readInData (const char *fileName, char* array[] ){
    char lineLth[SIZES_2];
    int i =0; 
    int length;
     // array for line length at 500 using defied size above.

    FILE * cfPtr; // pointer to file stream called cfPtrlist

    cfPtr = fopen(fileName,"r");// open file passed as argument to function to read only 

    if(!cfPtr) // i encapsulated in a bracket here and it threw an error

        return -1; // return an error message to locate where the problem is i am useing this to see if file opening is still a problem

    while (!feof(cfPtr)){ // while end of file signal is not reached
        
        fscanf(cfPtr,"%s",lineLth);// scan in each line
        length = strlen(lineLth);//  find the length of the line ie the word
        array[i] = (char*)malloc(length+1); //use +1 to allocate memory effectivly 
        strcpy(array[i], lineLth); // copy the string in the line ltth and pass 
        ++i; // increment counter
    }

    fclose(cfPtr); // close file
    return i;// return value
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
deburca98
  • 1
  • 2
  • You don't check if `fscanf` succeeds and somehow expect `feof` to predict the results of future operations and not just report on the past. – David Schwartz Jan 07 '21 at 22:11

1 Answers1

0

You output lineLth whether or not the call to fscanf succeeds. You need to process data only if you were successfully able to read data in. You can't use feof to predict whether or not a future operation will succeed. It's a status-reporting function that tells you about what worked in the past, not a prediction operation that tells you what will work in the future.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278