I am trying to implement a test program to describe what this function does:

int mystery( const char *s1, const char *s2 )
{
 for( ; *s1 != '\0' && *s2 != '\0'; s1++, s2++ ) {
if( *s1 != *s2 ) {
 return 0;
}//end if
 }//end for
 return 1;
}

The program compiles and runs fine, but everytime I enter two strings, I always get a result of 0, even if they are the same length. I just can't quite figure out what I am doing wrong. Any help would be much appreciated!

#include <stdio.h>
#define SIZE 80

int mystery( const char *s1, const char *s2 ); // prototype 7
int main( void )
{
    int result;

    char string1[ SIZE ]; // create char array
    char string2[ SIZE ]; // create char array

    result = mystery(string1, string2);

    puts( "Enter two strings: " );
    scanf( "%79s%79s", string1, string2);

    if (result == 1)
    {
        puts("The strings are the same length");
    }
    if (result == 0)
    {
        puts("The strings are different lengths");
    }

    return 0;

} // end main

int mystery( const char *s1, const char *s2 )
{
    for( ; *s1 != '\0' && *s2 != '\0'; s1++, s2++ ) {
        if( *s1 != *s2 ) {
            return 0;
        }//end if
    }//end for
    return 1;
}

`

What happens when you enter the same string twice?

You're supposed to be testing the two strings that the user entered, right?

So shouldn't you be calling the mystery function AFTER the user has typed those string in?

commented: Thank you!!!!! +0

First, you have not initialized the two strings, so they contain random data from the stack. Moschops is correct in that you need to initialize the strings before calling the mystery function. Also, this is NOT testing for length, but for equality of strings, so your output is misleading. IE, "foo" and "bar" will results in "The strings are of different lengths" even though they are not. Try this instead:

#include <stdio.h>
#define SIZE 80
int mystery( const char *s1, const char *s2 ); // prototype 7
int main( void )
{
    int result;
    char string1[ SIZE ]; // create char array
    char string2[ SIZE ]; // create char array

    puts( "Enter two strings: " );
    scanf( "%79s%79s", string1, string2);
    result = mystery(string1, string2);
    if (result == 1)
    {
        puts("The strings are the same");
    }
    if (result == 0)
    {
        puts("The strings are different");
    }
    return 0;
} // end main
int mystery( const char *s1, const char *s2 )
{
    for( ; *s1 != '\0' && *s2 != '\0'; s1++, s2++ ) {
        if( *s1 != *s2 ) {
            return 0;
        }//end if
    }//end for
    return 1;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.