0

Ok so i am writing a C program. The program is simple enough, when i run the program i give it a few parameter Ex ./proj1 cat hat bat, so then it asks me to input a list of words the program gives counts of how many times "cat", "hat", and "bat" occurs in that list. I have the program working great.

Example 
./pro1 cat hat bat
cat
.

(the program recognized a "." as the end of input)

Result:
cat:1
hat:0
bat:0

ok so my program runs perfectly in every test case i can think of, but I have to pass a series of tests that my professor has mas made. here is the code of that test.

char *args[] = {"./main", "cat", "hat","bat",NULL};
char *result[] = {"Looking for 3 words\n",
  "Result:\n",
  "cat:1\n",
  "hat:0\n",
  "bat:0\n"};
FILE *out;
FILE *test;
test=fopen("test","w");
int i;
char *buffer=malloc(100*sizeof(char));

out = fopen("smp0.in", "w");
fprintf(out, "cat\n");
fprintf(out, ".\n");
fclose(out);

freopen("smp0.in", "r", stdin);


freopen("smp0.out", "w", stdout);

quit_if(main(4, args) != EXIT_SUCCESS);

fclose(stdin);
fclose(stdout);

out = fopen("smp0.out", "r");


for (i = 0; i < 5; i++) {
    quit_if(fgets(buffer, 100, out) == NULL);
    quit_if(strcmp(buffer, result[i]));
}


fclose(out);
return EXIT_SUCCESS;
 }

ok so sending the quit_if() is the method that makes it fail. specifically

   quit_if(strcmp(buffer, result[i]));

My output when i run the program is exactly as described. But between freopen() diverting stdout to a file and then reading it back it has changed somehow.

  Result:
  cat:1
  hat:0
  batÿ:0

is what the output becomes, but it is not like that before the file write and read, and for some reason it is always that weird y character.

any advice would be greatly appreciated. Sorry for not posting more code but it's because it is a school project. I am confident that it is the test that is wrong in some way and not my code, fixing the test is part of the project as well.

4

1 回答 1

2

请参阅上一个问题的答案:

https://stackoverflow.com/a/4906442/2009431

似乎当从您的标准输入文件中读回点时,它附加了一个 EOF 令牌(有意义),通常不会成为用户输入的一部分。然后,不知何故(不确定,因为我们看不到您的代码)您的 main() 函数以那个奇怪的 y 字符的形式将该 EOF 字符附加到“bat”上(有关原因的详细信息,请参见链接答案)。

如果我是对的,也许这可以被认为是测试中的错误?

于 2013-02-01T22:30:24.143 回答