-1

I wan´t to read a file (10K float numbers each in a own row) and find the max_val element of it (I´m not that far now). I managed to get the file into a char array but I need it to be a float array to be abled to find the max value.

Thanks for any help.

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

int main(int argc, char* argv[]){

    char nameDatei[100];
    
    if(argv[1] != NULL) {
        strcpy(nameDatei, argv[1]);
    } else {
        printf("type in the name of the file: ");
        scanf("%s", nameDatei);
    }
    
    //read file;
    FILE *fPointer;
    fPointer = fopen("findMaxOfFloats.txt", "r");

    //save
    char singleLine[100];
    char content[10000][100];
    int i = 0;
   
    while (!feof(fPointer)){
        if (fgets(content[i], sizeof(singleLine), fPointer) != NULL)
            i++;    
    }

    fclose(fPointer);
    
    //print the array
    for(int loop = 0; loop < 10000; loop++){
    printf("%s", content[loop]);
    }
    

   //find max...

    return 0;
}
  • 2
    See [Why is `while(!feof(fp))` always wrong?](https://stackoverflow.com/questions/5431941). The correct way to write the loop is `while (fgets(singleLine, sizeof(singleLine), fPointer) != NULL)) { ... }` – user3386109 Oct 24 '22 at 21:35
  • 1
    And if the only goal is to find the maximum value, then you don't need an array. All that's needed is a `float` variable that stores the maximum seen so far. Read a line, extract the value using `sscanf` or `strtod`, then compare with the maximum, and update the maximum if needed. – user3386109 Oct 24 '22 at 21:42
  • Okay, thats a good idea. But if i want to do it "my way". Do you have an idea how to make the input float or convert it to float? – Enno Mühlbauer Oct 24 '22 at 21:44
  • This really isn't the right site to ask "how do I input a floating point value" or insist that you do it 'your way'. That is what the textbook is for. Implement what it says and if you have trouble, then ask here. – Weather Vane Oct 24 '22 at 21:59
  • Why should I use floats and double instead? The code works now i used atof() to convert the strings. Thanks anyway :) – Enno Mühlbauer Oct 24 '22 at 22:00
  • 1
    Because `float` is inferior, and `double` is the natural type of the language, like `int` is for integers. `float` is 1980s and obsolete textbooks. You don't use `short` for small integers except when it is somehow necessary to save memory use. You can't even implement an accurate basic 8-digit calculator with `float`. – Weather Vane Oct 24 '22 at 22:01
  • If you use `sscanf`, it will convert to `float` if you use the `%f` conversion specifier. If you use `strtod`, it will convert to `float` when you assign the returned value to a `float` variable. If by "your way", you mean you want to declare a million byte array `content` on the stack, and then fill it with the contents of the file, then good luck with that. – user3386109 Oct 24 '22 at 23:05

1 Answers1

0

A few issues ...

  1. You read a line into singleLine but don't copy it into content
  2. feof is bad--just check the fgets return value
  3. You want content to be double and not just a char array.
  4. After doing fgets, you can/should use strtod to convert the string in singleLine into a binary/floating point value.
  5. You want to maintain a count of the number of lines read (i.e. the number of valid elements in content).
  6. You get a filename from either argv[1] or scanf but then use a hardwired name instead.
  7. You don't check the return value of fopen

Here is the refactored code. It is annotated:

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

#define MAXCONTENT      10000

int
main(int argc, char *argv[])
{

    char nameDatei[100];

    if (argv[1] != NULL) {
        strcpy(nameDatei, argv[1]);
    }
    else {
        printf("type in the name of the file: ");
        scanf("%s", nameDatei);
    }

    // read file;
    FILE *fPointer;

// NOTE/BUG: You get a filename from either argv[1] or scanf but don't use it
#if 0
    fPointer = fopen("findMaxOfFloats.txt", "r");
#else
    fPointer = fopen(nameDatei, "r");
    if (fPointer == NULL) {
        perror(nameDatei);
        exit(1);
    }
#endif

    // save
    char singleLine[100];
#if 0
    char content[10000][100];
#else
    double content[MAXCONTENT];
#endif
#if 0
    int i = 0;
    while (!feof(fPointer)) {
        if (fgets(content[i], sizeof(singleLine), fPointer) != NULL)
            i++;
    }
#else
    int count = 0;

    // read in all lines until EOF
    while (fgets(singleLine,sizeof(singleLine),fPointer) != NULL) {
        // don't overflow the array
        if (count >= MAXCONTENT) {
            printf("count too large\n");
            exit(1);
        }

        // decode the number
        char *cp;
        content[count] = strtod(singleLine,&cp);

        // check for syntax error
        if (*cp != '\n') {
            printf("syntax error: %s",singleLine);
            exit(1);
        }

        ++count;
    }
#endif

    fclose(fPointer);

    // print the array
    for (int idx = 0;  idx < count;  ++idx)
        printf("%g\n", content[idx]);

    // find max... [and min, too ;-)]
    double max = content[0];
    double min = content[0];
    for (int idx = 0;  idx < count;  ++idx) {
        // get the current value
        double cur = content[idx];

        // set new maximum
        if (cur > max)
            max = cur;

        // set new minimum
        if (cur < min)
            min = cur;
    }

    printf("min=%g max=%g\n",min,max);

    return 0;
}

In the above code, I've used cpp conditionals to denote old vs. new code:

#if 0
// old code
#else
// new code
#endif

#if 1
// new code
#endif

Note: this can be cleaned up by running the file through unifdef -k

Craig Estey
  • 30,627
  • 4
  • 24
  • 48
  • You're welcome. If you'd like to express thanks in a "material" way, please upvote/accept my answer. See: [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers) – Craig Estey Oct 27 '22 at 22:08
  • Hello thank you a lot for your detailed explanation and correction of my code!! I managed to implement everything :) The inly remaining question is, why i shouldn´t use feof? Best regards Enno – Enno Mühlbauer Oct 27 '22 at 22:12
  • I can´t vote, not enough reputation. – Enno Mühlbauer Oct 27 '22 at 22:14