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.
In addition to the printf
/fprintf
problem, in any decent modern compiler, that code should be generating a warning that you're not assigning any initial value to i
.
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, e.g.
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.
精彩评论