Monday 26 September 2016

c - While loop doesn't seem to finish after EOF

I am trying to write a while-loop that terminates at the end of file. I have used
while(!feof(stdin)) in the code bellow, but the loop doesn't seem to terminate even if EOF is reached (I am reading from file). When executed in terminal, the program does all that is supposed to, but then keeps going for several seconds before "program.exe stopped working" window opens.
I have googled for almost several hours, tried different versions (variations for while (1) followed by int check = scanf("%d", &from); if (check == EOF) break;) and nothing worked for me.



The possibly problematic part of code:



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);
}


The entire code:



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;
}


Does anyone have any tip for what might be wrong? I will really appreciate any help!

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...