Issue
I am done with the input and process part of the program, but I don't know how to terminate the program with EOF. Here is my int main(void) code:
int main(void)
{
int size;
int n;
char preorder[26];
char inorder[26];
while(/* I don't know what to put on this part...*/)
{
for(n = 0; n < maxSize; n++)
{
preorder[n] = ' ';
inorder[n] = ' ';
}
preIndex = 0;
scanf("%s %s", preorder, inorder);
size = strlen(preorder);
struct node *root = constructTree(inorder, preorder, 0, (size - 1));
printPostorder(root);
printf("\n");
}
return 0;
}
Every function is working fine, I've checked them separately. Basically the user wants to end this program by pressing Ctrl + Z (I'm working on windows, so it's Z). I have to use EOF. Thx in advance
Solution
Check the return value of your input functions. scanf
will return the number of items stored or EOF if it encounters end-of-file.
As Anthon says, you can use while(1)
as your loop control, and use break;
to exit the loop.
while(1) {
if (scanf(...) == EOF)
break;
}
Don't be tempted to use the function called feof()
because it only checks a flag in the FILE structure, ie. it will only detect an EOF after you've tried to read it. It can be used in a multi-tiered error handling structure, though.
while(1) {
if (scanf(...) < N_elements_specified) {
if (feof(...)) {
/* EOF detected */
break;
} else {
/* some other cause of insufficient data */
}
}
}
Answered By - luser droog Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.