-3

I need to find the maximum number from file in.txt with content: 12 7 -14 3 -8 10 and then write it to file out.txt. Here is my full code:

#include <conio.h>
#include <stdio.h>

main() {
  int N, max;
  FILE*F;
  F = fopen("in.txt", "r");
  FILE*G;
  G = fopen("out.txt", "w");
  fscanf(F, "%d", &max);
  while (feof(F)) {
    fscanf(F, "%d", &N);
    if (max < N)
      max = N;
  }
  printf("max=%d", max);
  fprintf(G, "%d", max);
  fclose(F);
  fclose(G);
} 
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256

2 Answers2

0

In C++14, you could use std::max_element directly with std::istream_iterator:

std::ifstream inf("in.txt");
auto it = std::max_element(std::istream_iterator<int>(inf), std::istream_iterator<int>());

if (it != std::istream_iterator<int>()) {
    std::ofstream outf("out.txt");
    outf << *it << std::endl;
}

In C++11 and earlier, this seems to be undefined behavior (because istream_iterator is an InputIterator, but max_element expects a ForwardIterator), so in those variations of the language you will need to read the file in a container (most like std::vector) before using max_element.

0

Incorrect use of feof().

Do not use feof() to check if additional input is available. feof() reports that the previous I/O operation resulted in the end-of-file condition.

IOW, check the results of your input operations like fscanf().

Suggest:

int MaxFound = 0;
while (fscanf(F, "%d", &N) == 1) {
  if (MaxFound) {
    if (N > Max) {
      Max = N;
    }
  } else {
    MaxFound = 1;
    Max = N;
  }
}
if (MaxFound) {
  printf("max=%d\n", max);
} else {
  puts("max not found");
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256