简体   繁体   中英

program that writes the even and odd numbers

I was writting a program that can read a set of numbers file called dog.txt; and also writes to two file separating odd and even. i was able to compile my program however, the output expected is not the same which was supposed to be even numbers in one file called EVEN, odd numbers in file odd.

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
  int i;
  int even,odd;
  int num;

  if (argc != 4) {
    printf("Usage: executable in_file  output_file\n");
    exit(0);
  }

  FILE *dog = fopen(argv[1], "r");
  FILE *feven= fopen(argv[2], "w");
  FILE *fodd= fopen (argv[3], "w");
  while (fscanf(dog, "%d", &num) != EOF)
    {
      if (0==i%2){
        i++;
         printf("even= %d\n", num);
         }
      else if(i!=0){
       i++;
       printf("odd= %d\n", num);
      }
    }
  fclose(feven);
  fclose(fodd);
  fclose(dog);

  return 0;
}

output:

even= 1
odd= 2
even= 34
odd= 44
even= 66
odd= 78
even= 94
odd= 21
even= 23
odd= 54
even= 44
odd= 65
even= 78
odd= 68
even= 92

You're checking i % 2 , not num % 2 . I'm not even sure what i does in this example—perhaps you're planning on using it later.

while (fscanf(dog, "%d", &num) != EOF) {
    if (num % 2 == 0) {
        printf("even = %d\n", num);
    }
    else if(num != 0) {
        printf("odd = %d\n", num);
    }
}

I imagine the code to write these numbers to the files will come later, once you've fixed this bug.

The code contains no instructions to write into the output files. It only writes to stdout.

The printf function writes to the screen (more correctly, it writes to "standard output", but that is usually the screen). You want to write to a file. You have opened files called feven and fodd . To write to them, you would use the fprintf call, which works like printf except it takes an extra (left-most) argument, which is the FILE* that you want to write to, eg

FILE *fmyfile = fopen("myfile.txt", "w");
fprintf(fmyfile, "The magic number is %d!", 3);

Also, your results are incorrect, but that's an unrelated problem.

除了printf / fprintf问题之外,在任何体面的现代编译器中,该代码应该生成警告,表明您没有为i分配任何初始值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM