虽然在EOF之后循环似乎没有完成

时间:2017-12-17 19:00:08

标签: c while-loop eof

我正在尝试编写一个终止于文件末尾的while循环。我用过 代码中的while(!feof(stdin)),但即使达到了EOF(我正在从文件中读取),循环似乎也不会终止。当在终端中执行时,程序会执行所有应该执行的操作,但在#34; program.exe停止工作之前会继续运行几秒钟"窗口打开。 我用谷歌搜索了几个小时,尝试了不同的版本(while (1)的变体后跟int check = scanf("%d", &from); if (check == EOF) break;)并且没有任何效果。

代码中可能存在问题的部分:

while(!feof(stdin))
{
    check2 = scanf(" %d %d", &from, &to);
// some input checks with check2
    lcm1 = useky[from];

    if (from != (to-1))  
    {
        for (i = (from+1); i < to; i++) 
        {
            lcm2 = useky[i];
            lcm_temp = lcm_vypocet(lcm1,lcm2);
            lcm1 = lcm_temp;
        }       
    }
    printf("Vozidel: %lld\n", lcm1);
}

整个代码:

long long int lcm_vypocet(long long int x, long long int y) {
long long int a, b, t, gcd, lcm;

a = x;
b = y;

while (a != 0) {
t = a;
a = b % a;
b = t;
}

gcd = b;
lcm = x*(y/gcd);

return lcm;
}    

int main(int argc, char *argv[]) {

int i=0, check, check1=0, check2, highestIndex, from, to;    
int *useky, *useky_copy, *temp;
long long int lcm1, lcm2, lcm_temp;
char delimiter, check0;

printf("Pocty pruhu:\n");
useky = (int*) malloc(sizeof(*useky));
useky_copy = useky;

scanf("%1s", &check0);
if (check0!='{') 
{
    printf("Nespravny vstup.\n");
    exit(0);
}

for (i=0;;i++) 
{
    check = scanf(" %d %1s", &useky[i], &delimiter);
    highestIndex = i;

    if (check1==2) // break from the loop on end of input 
    {
        break;  
    }
    temp = (int*)realloc (useky, sizeof(*useky) + sizeof(int)); 
    if ( temp == NULL ) 
    {
        free(useky);
        printf("Nespravny vstup.\n");
        return 1;   
    }
    useky = temp;
}
printf("Trasy:\n");

while(!feof(stdin))
{
    check2 = scanf(" %d %d", &from, &to);
    lcm1 = useky[from];

    if (from != (to-1))  
    {
        for (i = (from+1); i < to; i++) 
        {
            lcm2 = useky[i];
            lcm_temp = lcm_vypocet(lcm1,lcm2);
            lcm1 = lcm_temp;
        }       
    }
    // lcm1 je výsledný počet vozidel.
    printf("Vozidel: %lld\n", lcm1);
}

free(useky_copy);   

return 0;
}

有没有人对可能出错的地方有任何提示?我真的很感激任何帮助!

0 个答案:

没有答案