-
Why the semicolon?
Why does this work?
Is the function of the semicolon after the while that the strcmp in the while compare's "zoekterm" with the previous "naam" and not that is loaded in that current execution of the while statement?
Code:
#include <stdio.h>
#include <string.h>
#define MAX 81
void main()
{
char naam[MAX];
char zoeknaam[MAX];
int leeftijd;
FILE *fptr;
fptr=fopen("c:/c/fprintf.txt","r");
if (fptr != NULL)
{
printf("Van welke persoon wil je de leeftijd kennen?\n");
scanf("%s",zoeknaam);
while (fscanf (fptr,"%s %d",naam, &leeftijd) != EOF && strcmp(naam,zoeknaam)!=0);
{
if (strcmp(naam,zoeknaam)==0)
{
printf("\nNaam: %s\n", naam);
printf("Leeftijd: %d\n\n", leeftijd);
}
else
{
printf("persoon niet gekend\n");
}
fclose(fptr);
}
}
else
{
printf("fout bij openen file\n");
}
}
example of a textfile:
Code:
bert 19
sylvie 17
koen 19
jimmy 19
jelle 19
-
Well, something is off there. Either the semicolon is unintentional, then it must be removed. Unlikely though, because of the fclose in the body.
Or the semicolon is intentional, then the indenting and block is very misleading and the semicolon poorly placed.
Code:
while(cond)
;
or
while(cond) {
}
are better methods to make bodyless loops.
Bodyless loops are used when everything that needs to be done is already done in the condition, which is the case here.
-
yeah,
it's placed stupid!
but I see it now, you just gotta see the 2 pieces apart:
thx for the help; greetings.
Code:
while (fscanf (fptr,"%s %d",naam, &leeftijd) != EOF && strcmp(naam,zoeknaam)!=0);
Code:
{
if (strcmp(naam,zoeknaam)==0)
{
printf("\nNaam: %s\n", naam);