向用户询问值,直到它们指示文件结束

时间:2019-05-20 23:50:31

标签: c

我无法充分使用EOF。

我想要什么: 程序执行时,应自动提示用户输入数字,并在用户通过键盘发出EOF信号时退出

实际情况: 当我运行该程序时,它坐在那里等待用户按下Enter键,然后提示用户输入数字。这使我的代码有问题

我不请任何人进行我的转让。我已经完成了99.8%。 IM对C编程来说是新的


#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h> // For exit() 

int main( ) {

    char c;
    while ( (c = getchar()) != EOF)  {

        int user_numbr = 0;
        int file_number = 0;
        int last_Appearance = 0;
        int index = 0;
        bool notFound;

        FILE *fptr;
        fptr = fopen("numbers.text", "r"); 

        printf("Enter a number: ");
        scanf("%d", &user_numbr);


        while ( !feof (fptr) ) {

            fscanf (fptr, "%d", &file_number);
            if ( feof (fptr) ) break;
            index++;

            if ( user_numbr == file_number ) {
                last_Appearance = index;
            }

        }
        fclose(fptr);

        if ( last_Appearance != 0) {
            printf("%d last appears in the file at position ", user_numbr);
            printf("%d\n", last_Appearance);
        }
        else if ((c = getchar()) != EOF)
            printf("%d does not appear in the file\n", user_numbr);

    }

    return 0;
}

2 个答案:

答案 0 :(得分:0)

假设您希望用户仅输入一次文件号,则可能应该移动

printf("Enter a number: "); scanf("%d", &user_numbr);

在while循环之上。

答案 1 :(得分:0)

我找到了解决方法。如果有此问题的任何人看到此帖子,我都会发布。

  
    

更正:     1)第一次while循环条件     2)如果有条件则为其他情况

  
int main( ) {

    char c;
    while ( !feof(stdin) )  {

        int user_numbr = 0;
        int file_number = 0;
        int last_Appearance = 0;
        int index = 0;
        bool notFound;

        FILE *fptr;
        fptr = fopen("numbers.text", "r"); 

        printf("Enter a number: ");
        scanf("%d", &user_numbr);


        while ( !feof (fptr) ) {

            fscanf (fptr, "%d", &file_number);
            if ( feof (fptr) ) break;
            index++;

            if ( user_numbr == file_number ) {
                last_Appearance = index;
            }

        }
        fclose(fptr);

        if ( last_Appearance != 0) {
            printf("%d last appears in the file at position ", user_numbr);
            printf("%d\n", last_Appearance);
        }
        else if ( !feof(stdin) )
            printf("%d does not appear in the file\n", user_numbr);

    }

    return 0;
}
相关问题