PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 30, 2022

[FIXED] How to stop program code by using EOF

 October 30, 2022     c, eof     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing