Results 1 to 6 of 6

Thread: [Using For Loop] Comparing 2 or more strings[No Cstring lib]

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

    Default [Using For Loop] Comparing 2 or more strings[No Cstring lib]

    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>

    void compare(char w1[200], char w2[200])
    {
        for (int w = 0; w1[w] != '\0'; w++)
            {
                if (((w1[w]== '\0') && (w2[w] != '\0')) || ((w2[w]== '\0') && (w1[w] != '\0')))
                {
                    printf("The strings are not equal\n");
                }
                if (w1[w] == w2[w])
                {
                    if ((w1[w] == '\0') && (w2[w] == '\0'))
                    {
                        printf("The strings are equal\n");
                    }
                }
                else
                {
                    printf("The strings are not equal\n");
                }
            }
    }

    int main(void)
    {
        char c1[200];
        char c2[200];

        printf("Enter the first string:\n");
        scanf("%s", c1);
        printf("Enter the second string:\n");
        scanf("%s", c2);

        compare(c1, c2);


        return EXIT_SUCCESS;
    }

    Whenever I run it (it doesn't do this all the time), it will not show if the strings are matching or not. What am I doing wrong?

    E: Also have this weird glitch where the printf's are not displaying until after the result has been displayed, this has been happening to almost every piece of code I write.
    Last edited by Recursive; 07-04-2012 at 11:33 PM. Reason: Glitch

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

    Default

    One critical thing I did not like when reading that is that you specified the size of the array within the function parameters. Arrays are always pass by reference! Do not put the size declaration within the function. It will automatically pick up the size from the passed parameter.

    Anyway I want you to look at both solutions below. Below the solutions will be an explanation as to why your method did not work.

    Your solution Fixed:
    C++ Code:
    #include <cstdio>
    #include <cstdlib>

    bool compare(char Str1[], char Str2[])
    {
        for (int I = 0; Str1[I] != '\0'; I++)
        {
            if (Str1[I] != Str2[I])
                return false;

            if (((Str1[I] == '\0') && (Str2[I] != '\0')) || ((Str1[I] != '\0') && (Str2[I] == '\0')))
                return false;
        }

        return true;
    }

    int main(void)
    {
        char c1[200], c2[200];

        printf("Enter the first string:\n");
        scanf("%s", c1);

        printf("\nEnter the second string:\n");
        scanf("%s", c2);

        if (compare(c1, c2))
            printf("\nThe strings are exactly the same!\n");
        else
            printf("\nThe strings are completely different!\n");


        return EXIT_SUCCESS;
    }


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

    bool compare(char Str1[], char Str2[])
    {
        int Size1 = 0, Size2 = 0, P = EOF, S = EOF;

        while (S != '\0')
        {
            P = Str1[Size1++];  //Just demonstrating how to get the length of chars in the array. Though you do not need this. You can use the compare method from the previous solution.
            S = Str1[Size1 + 1];
        }

        P = S = EOF;
        while (S != '\0')
        {
            P = Str2[Size2++];
            S = Str2[Size2 + 1];
        }

        if (Size1 != Size2)
            return false;

        for (int I = 0; I < Size1; I++)
            if (Str1[I] != Str2[I])
                return false;

        return true;
    }

    int main(void)
    {
        char c1[200], c2[200];
        int I = 0, J = 0, C = EOF;

        printf("Enter the first string:\n");
        while ((C = getchar()) != '\n' && C != EOF)
        {
            c1[I++] = (char) C;
        }
        c1[++I] = '\0';

        C = EOF; I = 0;
        printf("\nEnter the second string:\n");
        while ((C = getchar()) != '\n' && C != EOF)
        {
            c2[I++] = (char) C;
        }
        c2[++I] = '\0';

        if (compare(c1, c2))
            printf("\nThe two strings are exactly the same!\n");
        else
            printf("\nThe two strings are completely different!\n");


        return EXIT_SUCCESS;
    }


    The difference? With my method, you can implement realloc incase the string the user enters is too long. This would prevent a buffer overflow. You method must have 199 characters + 1 for the null for a grand total of 200 characters. Any more will cause undefined behaviour. Many programmers forget this and wonder where the security holes are.

    Anyway your method is shorter and still good so use it. Just posted mine for future reference and for a different insight on a different comparison method.

    Problem with your posted method:

    Every loop, you are checking if the characters are equal. The problem with this is that you then check again if both are null; if they aren't you're doing nothing.

    Basically for every character in the smaller string, you're printing whether the strings are equal or not at the very END and that is invalid. You have:

    C++ Code:
    if (W1[I] == W2[I]) //Sure we need to check if both are equal. If they are.. then why are you checking if both are null?
        if (W1[I] == '\0' && W2[I] == '\0')   //Why are you doing this? We already established that on the previous line they are equal.. The only reason i could think of that you may have put this here is to check if the length of both the strings are the same and if they are then they are equal. This is NOT a good way to do that.

    In the above, i think you're trying to see if both strings have the same length. And if they do, then and only then you print they are equal. The truth is that at the end of your forloop, both these conditions will be true. W1 will equal W2 and they will both be NULL. Thus it will always return true if the strings are the same length but different characters. Any string with the same length will be considered equal. It would be better if you compared char for char and if one does not equal the other, return false immediately! When both strings do NOT have a null at the same spot, also return false. Otherwise who cares about the rest. Let the for loop continue and finally return true at the very end if it never returned false in the first place.
    Last edited by Brandon; 07-05-2012 at 01:00 AM.
    I am Ggzz..
    Hackintosher

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

    Default

    Sick! Here it is I added something extra to it

    C++ Code:
    using namespace std;
    #include <cstdio>
    #include <cstdlib>

    int count(char c[])
    {
        int i;
        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 main(void)
    {
        char c1[200];
        char c2[200];

        printf("Enter the first string:\n");
        scanf("%s", c1);
        printf("Enter the second string:\n");
        scanf("%s", c2);

        if (compare(c1, c2))
        {
            printf("The strings are equal\n");
        }
        else
        {
            printf("The strings are not equal\n");

        }


        return EXIT_SUCCESS;
    }

    Thanks again Brandon, really helps when you write your logic down on paper and then start from there to implement it

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

    Default

    I "think" the Count function should be ++I OR I = N but I haven't tested it and you may be right. Though I must say good idea to make the counting a function. It'll be useful.
    Last edited by Brandon; 07-05-2012 at 05:06 AM.
    I am Ggzz..
    Hackintosher

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

    Default

    What is the difference b/w i++ and ++i?

  6. #6
    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
    What is the difference b/w i++ and ++i?
    I++ only increments at the end of every loop. ++I increments immediately.

    I was also confused when I first stumbled across this.. Here is the answer:

    C++ Code:
    T& operator++()            //Pre increment (++T)
    {
        return ((*this) + 1);    //or return ++(*this);   //We increment the value then return it.
    }

    T& operator++(int I)    //Post Increment. (T++)
    {
        T Temp(*this);   //Create a temporary copy.
        ++(*this);         //Increment the actual value.
        return Temp;    //Return our temporary copy. Basically returns the un-incremented copy. Aka the same value as we had.
    }

    In the above, ++T will be the same as T = T + 1;
    Whereas T++ is the same as T. Why? Because T++ returns the temporary value. Aka a copy of itself. When T is called after the incrementation, T will contain a value of itself + 1.

    So:

    C++ Code:
    int K = 0;
    int L = 0;

    std::cout<< K++;   //This will print 0!! Because the returned value is a copy of itself.
    std::cout<< K;        //This will print 1!! Because K was incremented on the previous line.

    std::cout<<  ++L;  //Returns 1, not 0. Because ++L Increments first then returns the incremented value. NOT a copy/temporary.
    I am Ggzz..
    Hackintosher

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
  •