简体   繁体   English

如何使用 EOF 作为结束循环的条件? C

[英]How to use EOF as the condition to finish the loop? In C

I'm making somewhat like an othello game.我做的有点像黑白棋游戏。 I receive a file that contains strings, and i have to read and process them, making the board as it goes.我收到一个包含字符串的文件,我必须读取并处理它们,从而制作电路板。 Example of the file received:收到的文件示例:

  1. Alejandro,B亚历杭德罗,B
  2. Federico,N费德里科,N
  3. B
  4. D6 D6
  5. C4 C4
  6. G5 G5

then i would convert the characters to numbers, so it can fit in the int board[8][8] i use然后我会将字符转换为数字,这样它就可以放入我使用的int board[8][8]

I was expecting that when it reaches the EOF it would get out of the loop, but instead it never stops the loop and keeps reapeting the last line with the printf. This is in the main function:我原以为当它到达 EOF 时它会退出循环,但它永远不会停止循环并不断重复最后一行 printf。这是主要的 function:

while( EOF != 1 && *error != 1)
    {
        tomaJugada(&fp,jugada);  //takes 1 line of the file
        toupper(jugada[0]);      
        int columna = convierte_a_int(jugada[0])-1;  //converts the letter to a number
        int fila =  (jugada[1]-'0')-1;               //converts the char number to int number
        printf("columna %i, fila %i \n",columna, fila);   
    }

This is the auxiliary function:这是辅助 function:

void tomaJugada(FILE** fp, char jugada[])
{    
    fgets(jugada,5,*fp);
    jugada[2] = '\0';
    //jugada[strcspn(jugada, "\n")] = 0;
}

I have seen people using thi:我见过人们使用 thi:

int ch = getc(fp);
  while (ch != EOF){...

but it would consumme data that i need to use, maybe i'm using it wrong?但它会消耗我需要使用的数据,也许我用错了?

Resumming: i want to use all the data in the file, reach de EOF, and end the loop.恢复:我想使用文件中的所有数据,到达de EOF,并结束循环。 How can i put the condition for the EOF?我如何设置 EOF 的条件?

I hope i explained myself well, i appreciate any help我希望我能很好地解释自己,感谢任何帮助

EOF in c is just a constant (typically -1), EOF != 1 would always evaluate to the same (that is guaranteed to be true as EOF will always be negative). c 中的 EOF 只是一个常量(通常为 -1), EOF != 1的计算结果始终相同(保证为真,因为 EOF 始终为负)。 What you need to do is to check if fgets returns null pointer (that is in the tomaJugada function) and when that happens, then either an error occurred or you've reached the end of the file.您需要做的是检查 fgets 是否返回 null 指针(在tomaJugada函数中),当发生这种情况时,要么发生错误,要么您已经到达文件末尾。 To disambiguate between the two you could use the feof function for instance.例如,要消除两者之间的歧义,您可以使用feof function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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