简体   繁体   English

而在C中使用EOF时

[英]while with EOF in C

I'm trying to read the data from a txt file with the following code but it's print only the first line from file. 我正在尝试使用以下代码从txt文件读取数据,但它仅打印文件的第一行。

int main() {
    int chave;
    char ordem[5];
    struct tTree *arvore = (struct tTree*)malloc(sizeof(struct tTree));
    arvore->raiz = NULL;
    scanf("%s", ordem); 
    printf("%s\n", ordem);
    setbuf(stdin, NULL);  
    do {
        scanf("%d", &chave);
        insere(criaItem(chave), arvore);
        setbuf(stdin, NULL); 
    } while(chave != EOF);

    if(strcmp(ordem, "PRE") == 0) {
        pre(arvore->raiz);
    }
    else if(strcmp(ordem, "POS") == 0){
        pos(arvore->raiz);
    }
    else if(strcmp(ordem, "IN") == 0){
        in(arvore->raiz);
    }
    printf("%d\n", altura(arvore->raiz)-1);
    system("pause");   
}
while (scanf("%d", &chave) == 1)
{
    insere(criaItem(chave), arvore);
    printf("Read: %d\n", chave);  // Debugging
    // setbuf(stdin, NULL);  // Pointless once there's been an I/O operation on stdin
}

This tests for EOF and other errors correctly, with the test up front. 可以预先进行EOF和其他错误的正确测试。 Almost always, it is best to do the read operation and test that it succeeded at the start of the loop. 几乎总是,最好执行读取操作并在循环开始时测试它是否成功。

There were a large number of problems with what you'd written, not least of which was that typing -1 as an input value would have terminated your loop. 您编写的内容存在很多问题,尤其是键入-1作为输入值会终止循环。

scanf() will return EOF, but not put it into chave . scanf()返回 EOF,但不会将其放入chave中 Shouldn't your code look something more like this? 您的代码不应该看起来像这样吗?

int ret;
do {
    ret = scanf("%d", &chave);
    if ( ret == 1) {
        insere(criaItem(chave), arvore);
        setbuf(stdin, NULL); 
    }
} while( ret != EOF);

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

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