Results 1 to 15 of 15

Thread: [WHAT]Exit Procedure[DOES IT DO]

  1. #1
    Join Date
    Dec 2011
    Location
    -bash
    Posts
    515
    Mentioned
    0 Post(s)
    Quoted
    27 Post(s)

    Question [WHAT]Exit Procedure[DOES IT DO]

    In the code below, would the exit command exit the for-loop as well or just the if statement?


    C++ Code:
    for(int v = 0; WhatToSearch[v] != '\0'; v++)
                {
                    N[v] = SearchString[c];
                    N2[v] = WhatToSearch[v];
                    c++;
                   
                    if (N[v] != N2[v])
                    {
                        exit;
                    }
                }

  2. #2
    Join Date
    Mar 2012
    Location
    127.0.0.1
    Posts
    3,383
    Mentioned
    95 Post(s)
    Quoted
    717 Post(s)

    Default

    Exits the whole procedure, to just exit the for loop, make it break, not exit.

  3. #3
    Join Date
    Dec 2011
    Location
    -bash
    Posts
    515
    Mentioned
    0 Post(s)
    Quoted
    27 Post(s)

    Default

    Thanks dude

  4. #4
    Join Date
    Feb 2011
    Location
    The Future.
    Posts
    5,600
    Mentioned
    396 Post(s)
    Quoted
    1598 Post(s)

    Default

    Quote Originally Posted by NKN View Post
    Exits the whole procedure, to just exit the for loop, make it break, not exit.
    Wow.. No guessing allowed . This isn't Pascal. Something like that could screw him up bad and he wouldn't know what messed him up especially if it's for a program of around 500+ lines.

    Quote Originally Posted by Chig View Post
    Thanks dude
    EXIT is an inheritted function from C and it does not exit any loops and certainly not any procedures! It will exit the entire "process". Meaning your program is going to close/terminate with whatever parameters you supply to exit.

    It's definition is:

    C++ Code:
    void exit(int status);

    Where status is the return code the process should exit with. It terminates a process normally and does the regular cleanup.

    exit(10) is the same as doing return 10 from main:

    C++ Code:
    int main()
    {
          return 0;  //same as Exit(0);   Difference is that Exit can close the program from anywhere. Whereas return will returns from the function it's called in, exit can exit the program from anywhere; not just main.
    }
    Last edited by Brandon; 07-06-2012 at 06:51 PM.
    I am Ggzz..
    Hackintosher

  5. #5
    Join Date
    Dec 2011
    Location
    -bash
    Posts
    515
    Mentioned
    0 Post(s)
    Quoted
    27 Post(s)

    Default

    What about exit(EXIT_SUCCESS)? OR exit(EXIT_FAILURE)? What is difference b/w the 2 of them and what would they do if used in the same code above?

    E: I give up! Brandon please help!

    This program is supposed to acquire a string from the user then acquire another sub-string from the user then it is supposed to check for the sub-string within the original string and return the value of the first letter of this sub-string within the original string.

    By value, I mean location

    C++ Code:
    //============================================================================
    // Name        : Tut2.cpp
    // Author      :
    // Version     :
    // Copyright   : Your copyright notice
    // Description : Hello World in C++, Ansi-style
    //============================================================================

    using namespace std;
    #include <cstdio>
    #include <cstdlib>

    int count(char c[])
    {
        int i = 0;
        for (int n = 0; c[n]!='\0'; n++)
        {
            i++;
        }
        return i;
    }

    bool compare(char w1[], char w2[])
    {
        for (int w = 0; w1[w] != '\0'; w++)
        {
            if (w1[w] == w2[w])
            {
                if ((w1[w] == '\0') && (w2[w] == '\0') && (count(w1)== count (w2)))
                {
                    return true;
                }
            }
            else
            {
                return false;
            }
        }
        return true;
    }

    int FindSearch(char SearchString[],char WhatToSearch[])
    {
        char SS[200];
        char WS[200];

        for(int b = 0; SearchString[b] != '\0'; b++)
        {
            if (WhatToSearch[0] == SearchString[b])
            {
                int c = b;

                for(int v = 0; (v - 1) < count(WhatToSearch); v++)
                {
                    SS[v] = SearchString[c];
                    WS[v] = WhatToSearch[v];
                    c++;

                    if(WS[v] == '\0')
                    {
                        if (compare(SS, WS))
                        {
                            return b;
                        }
                    }

                }

            }
        }
        return -1;
    }

    int main()
    {
        char T[200];
        char L[200];

        printf("Write a string\n");
        scanf("\n%s", T);

        printf("\nWhat sub-string do you want to look for within %s? \n", T);
        scanf("%s", L);

        if ((FindSearch(T, L)) >= 0)
        {
            printf("\nThe sub-string occurs at location %i", (FindSearch(T, L)));
            printf("\n");
        }
        else
        {
            printf("The sub-string %s is not located within the string %s\n", L, T);
        }
        /*if ((FindSearch(T, L)) == -2)
        {
            printf("The sub-string %s is not equal to the string %s\n", L, T);
        }*/




        return EXIT_SUCCESS;
    }

    Problem: It searches the search array to the end instead of just searching for the length of the whattosearch.
    Last edited by Recursive; 07-06-2012 at 09:44 PM. Reason: Frustration

  6. #6
    Join Date
    Feb 2011
    Location
    The Future.
    Posts
    5,600
    Mentioned
    396 Post(s)
    Quoted
    1598 Post(s)

    Default

    Well due to the question you just asked me, I'm not 100% sure you understood the definition I gave. I'd like you to run this code and tell me the output or a description of what happened.

    In physics and stuff we usually do something like:

    Theory 1: The program will close abruptly and it will not call anything else. Everything will be destructed with a return code..
    Theory 2: The program will run successfully, break out of the for loop, Do the next statement, and terminate with a return code..
    Theory 3: The program will run successfully, break out of the two functions, continue to the last statement, and terminate successfully with a return code..

    Result: ???


    Pick a theory, think of why you chose it then I'd like you to try it and see what I mean. If you were correct, you understood the definition, if not, explain why you chose your theory and why you think you may be right or wrong.

    C++ Code:
    #include <windows.h>
    #include <iostream>
    #include <cstdlib>

    int Status = 0;

    void Tracer()
    {
        std::cout<<"\n\nProgram Terminated prematurely but cleanly (Destructors called; Stack Unwinded)!\nNo other functions were called."<<std::endl;
        std::cout<<"\nProgram Returned: ";
        switch (Status)
        {
            case EXIT_FAILURE:  std::cout<<"EXIT_FAILURE("<<EXIT_FAILURE<<")"<<std::endl;
            break;

            case EXIT_SUCCESS:  std::cout<<"EXIT_SUCCESS("<<EXIT_SUCCESS<<")"<<std::endl;

            default:    std::cout<< GetLastError() <<std::endl;
            break;
        }
        std::cout<<"\nTheory 1."<<std::endl;
        std::cin.get();
    }

    void TestingForLoopExitF()
    {
        Status = EXIT_FAILURE;
        for (int I = 0; I < 10; I++)
        {
            std::cout<<"The Value of I is: "<< I << std::endl;

            if (I >= 2)
                exit(Status);
        }
        std::cout<<"For Loop Was Just Broken Only."<<std::endl;
        std::cout<<"\nTheory 2."<<std::endl;

    }

    void TestingForLoopExitS()
    {
        Status = EXIT_SUCCESS;
        for (int I = 0; I < 10; I++)
        {
            std::cout<<"The Value of I is: "<< I << std::endl;

            if (I >= 2)
                exit(Status);
        }
        std::cout<<"For Loop Was Just Broken Only"<<std::endl;
        std::cout<<"\nTheory 3."<<std::endl;
    }

    int main()
    {
        atexit(&Tracer);
        TestingForLoopExitF();

        TestingForLoopExitS();

        std::cout<<"Exit didn't work as we expected! This statement printed successfully!"<<std::endl;

        std::cin.get();
    }
    Last edited by Brandon; 07-06-2012 at 09:51 PM.
    I am Ggzz..
    Hackintosher

  7. #7
    Join Date
    Mar 2012
    Location
    127.0.0.1
    Posts
    3,383
    Mentioned
    95 Post(s)
    Quoted
    717 Post(s)

    Default

    Oh, I didn't even look, lol.

    Assumed it was Pascal.
    My bad.

  8. #8
    Join Date
    May 2007
    Posts
    526
    Mentioned
    12 Post(s)
    Quoted
    109 Post(s)

    Default

    Also, bear in mind that

    Quote Originally Posted by Chig View Post

    C++ Code:
    ...

        for (int w = 0; w1[w] != '\0'; w++)
        {
            if (w1[w] == w2[w])
            {
                if ((w1[w] == '\0') && (w2[w] == '\0') && (count(w1)== count (w2)))
                {
                    return true;
                }
            }
            else
            {
                return false;
            }
        }
        return true;
    }

    int FindSearch(char SearchString[],char WhatToSearch[])
    {
        char SS[200];
        char WS[200];

        for(int b = 0; SearchString[b] != '\0'; b++)
        {
            if (WhatToSearch[0] == SearchString[b])
            {
                int c = b;

                for(int v = 0; (v - 1) < count(WhatToSearch); v++)
                {
                    SS[v] = SearchString[c];
                    WS[v] = WhatToSearch[v];
                    c++;

                    if(WS[v] == '\0')
                    {
                        if (compare(SS, WS))
                        {
                            return b;
                        }
                    }

                }

            }
        }
        return -1;
    }
    is flawed as you assume every string is automatically null-terminated. As you are writing C++ code, I suggest you to use for example STL library's string class instead.

  9. #9
    Join Date
    Dec 2011
    Location
    -bash
    Posts
    515
    Mentioned
    0 Post(s)
    Quoted
    27 Post(s)

    Default

    Quote Originally Posted by superuser View Post
    Also, bear in mind that



    is flawed as you assume every string is automatically null-terminated. As you are writing C++ code, I suggest you to use for example STL library's string class instead.
    This is a lab assignment, so we are not allowed to use the cstring class

    EDIT: What part of it is flawed btw, just wondering?

  10. #10
    Join Date
    May 2007
    Posts
    526
    Mentioned
    12 Post(s)
    Quoted
    109 Post(s)

    Default

    Quote Originally Posted by Chig View Post
    This is a lab assignment, so we are not allowed to use the cstring class

    EDIT: What part of it is flawed btw, just wondering?
    Well, for instance:

    c++ Code:
    for (int w = 0; w1[w] != '\0'; w++)

    What if the 'string' is not null-terminated. What you think will happen?

    Also, CString is part of ATL/MFC framework I'm afraid and thus not standard. std::string was the one I meant. I'm sure you are allowed to use STL?

  11. #11
    Join Date
    Dec 2011
    Location
    -bash
    Posts
    515
    Mentioned
    0 Post(s)
    Quoted
    27 Post(s)

    Default

    By null terminated, do you mean what if the string does not contain the '\0' at the end? In which case, I say they all do.

  12. #12
    Join Date
    Feb 2011
    Location
    The Future.
    Posts
    5,600
    Mentioned
    396 Post(s)
    Quoted
    1598 Post(s)

    Default

    Quote Originally Posted by Chig View Post
    By null terminated, do you mean what if the string does not contain the '\0' at the end? In which case, I say they all do.
    That is what he means. Basically in Cpp, all strings should be null terminated. Meaning that as soon as an iterator hits the '\0', we know that that was the end of the string. There are other types of strings that are double null terminated but both of these are inheritted from C.

    C doesn't contain the stl library and so the standard is to ensure all strings are null terminated and to use fgets for getting input rather than scanf. Scanf isn't buffer overflow protected that's why.

    So with all that said, if you were to attempt to get a string with spaces, scanf will give you trouble unless of course you know regexes and you do: "scanf("%[^\n]s", Variable)". This is because scanf stands for scan formatted and that's exactly what it does (__format(##X)__). Something like that. It's some awkward preprocessor define. It has no regard for special characters or anything else.

    fgets will continue to grab characters until the enter key is pressed and it's MUCH safer. BUT beware that fgets will also include that newline from the enter key into your string so it is your job to remove it after grabbing input but setting it null! If a user enters too many characters with fgets, it will throw. With Scanf, it will keep allowing it and cause you a TON of problems. Remember what I told you in the last post about malloc to prevent and realloc?

    With all that said, let us assume that you take these risks because you cannot use C++ STL and guarantee me that those strings are null terminated then:

    C++ Code:
    #include <cstdio>
    #include <cstdlib>

    int count(char c[])
    {
        int i = 0;
        for (int n = 0; c[n]!='\0'; n++)
        {
            i++;
        }
        return i;
    }

    bool compare(char w1[], char w2[])
    {
        for (int w = 0; w1[w] != '\0'; w++)
        {
            if (w1[w] == w2[w])
            {
                if ((w1[w] == '\0') && (w2[w] == '\0') && (count(w1)== count (w2)))
                {
                    return true;
                }
            }
            else
            {
                return false;
            }
        }
        return true;
    }

    int FindSearch(char SearchString[], char WhatToSearch[])
    {
        char SS[200];
        char WS[200];
        int Count = count(WhatToSearch);

        for(int b = 0; SearchString[b] != '\0'; b++)
        {
            if (SearchString[b] == WhatToSearch[0]) //So you are checking if the first letter of the search string is in the larger string. Correct!
            {
                for(int v = 0; v < Count; v++)    //No need for v - 1. You are searching for your entire string in the larger from the starting point of C.
                {
                    WS[v] = SearchString[b + v];  //You want to create a substring starting from b until the length of v from the larger string.
                    if (v == Count - 1)           //If we are at the end of the string..
                    {
                        WS[Count + 1] = '\0';     //Null terminate the string.
                        if (compare(WS, WhatToSearch))  //Compare our constructed string with the one we are trying to find.
                            return b;                   //If the two strings did match, return the position it was found at.
                    }
                }
            }
        }
        return -1;
    }

    int main()
    {
        char T[200];
        char L[200];

        printf("Write a string\n");
        fgets(T, sizeof(T), stdin);
        T[count(T) - 1] = '\0';         //Removes the newline.

        printf("\nWhat sub-string do you want to look for within %s? \n", T);
        fgets(L, sizeof(T), stdin);
        L[count(L) - 1] = '\0';         //Removes the newline.

        if ((FindSearch(T, L)) >= 0)
        {
            printf("\nThe sub-string occurs at location %i", (FindSearch(T, L)));
            printf("\n");
        }
        else
        {
            printf("The sub-string %s is not located within the string %s\n", L, T);
        }

        return EXIT_SUCCESS;
    }


    The difference is that you aren't constructing your strings right. Also you MUST terminate them with the null character! Do not forget this.
    Now I know you make ask why does it only get the first occurance if any. Well that's because we return the position as soon as it's found. If you want all occurances, you must make an array of integers, set all values to -1. For every position the string is found, set that position to the correct value. Return the array and print every position that is not -1.
    Last edited by Brandon; 07-06-2012 at 10:43 PM.
    I am Ggzz..
    Hackintosher

  13. #13
    Join Date
    Dec 2011
    Location
    -bash
    Posts
    515
    Mentioned
    0 Post(s)
    Quoted
    27 Post(s)

    Default

    Thank you for your solution Brandon, but what is this part doing?

    C++ Code:
    fgets(T, sizeof(T), stdin);
        T[count(T) - 1] = '\0';

    EDIT: Nvm, I just read your first post but can you explain those parameters in fgets()?

    Also in this assignment, we are assuming that the user will not be typing in any special characters and it is just solely letters. So no need for fgets(). So does that mean space has the character '\0'? Or not?

  14. #14
    Join Date
    Feb 2011
    Location
    The Future.
    Posts
    5,600
    Mentioned
    396 Post(s)
    Quoted
    1598 Post(s)

    Default

    Quote Originally Posted by Chig View Post
    Also in this assignment, we are assuming that the user will not be typing in any special characters and it is just solely letters. So no need for fgets(). So does that mean space has the character '\0'? Or not?
    Well I did not assume when writing it that you won't be using spaces. I assumed that anything goes.

    Scanf (without a regex) breaks out of the input procedure and moves to the next line of code when space is pressed followed by enter. After the space, any characters enter will NOT be considered part of the string.

    Scanf vs. fgets

    Example:
    C++ Code:
    scanf("%s", Input);   //Suppose I entered "Wow this stuff is so cool";

    In the above, without a regex, input will only contain: "Wow\0". With fgets(), it will contain the entire string: "Wow this stuff is so cool".

    Space does not have the same ASCII value as the NULL character. By default, the null character is appended to the input buffer upon the enter key being press "UNLESS!" it is in a while loop. In a while loop, it will append the null character when the enter key is pressed OR when the while loop is broken assuming it is not infinite.

    Respectable Code:
    Though I always append the null myself as good practice because you never want to get caught off-guard when writing C-code. You will be a respected coder by showing you know what you are doing when you append what is supposed to be there. Do not confuse this with C++ style strings. Meaning don't go appending the Null char at the end of an std::string. It's not bad but well picky ppl frown upon it or say "omg what a useless..." or noobs will say: "omg double null terminated std::string!! wtf.. i can't use this code!".

    All that being said.. You can remove the fgets and use scanf just like you had it before provided that the string entered is <= 199 characters (1 for the null).


    As per your request:
    C++ Code:
    char* fgets (char* str, int num, FILE * stream);

    char* str as it suggests is a pointer to a character array that will be filled with the info from the stream parameter.

    int num is the maximum amount of input to accept! This is what prevents overflow. Sizeof(T) in my example is equal to: Sizeof(T)/sizeof(char) which gets the amount of elements in the array given. The reason I removed the /sizeof(char) is because sizeof(char) is 1. There's no point dividing by 1 right? Any other type will require it. Example: Integer array: sizeof(ArrayToCheck)/sizeof(int); OR sizeof(ArrayToCheck)/sizeof(ArrayToCheck[0]); Same thing.

    FILE* stream is a pointer to a file stream to read from. To read from the console buffer, stdin can be passed to the function instead.

    Btw.. I noticed my posts are usually a bit extra long. Hope you don't mind.
    Last edited by Brandon; 07-06-2012 at 11:45 PM.
    I am Ggzz..
    Hackintosher

  15. #15
    Join Date
    Dec 2011
    Location
    -bash
    Posts
    515
    Mentioned
    0 Post(s)
    Quoted
    27 Post(s)

    Default

    LOl never been a problem for me; as long as I understand I'm good to go

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •