1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

A little C++ question

Discussion in 'C, C++, C#' started by bk071, Sep 21, 2014.

Thread Status:
Not open for further replies.
  1. bk071

    bk071 Jr. Executive VIP Jr. VIP Premium Member

    Joined:
    Nov 24, 2010
    Messages:
    3,104
    Likes Received:
    7,915
    Occupation:
    I don't have a job
    Location:
    .............
    ---- THREAD CLOSED 09/21/2014 ----
    Hey folks,

    Here's a little program I wrote.

    Code:
    #include<iostream>
    #include<conio.h>
    
    using namespace std;
    
    int main ()
    {
    	char a[1000], b[1000];
    	int count=0;
    	cout<<endl<<"Enter some characters in string a "<<endl;
    	gets(a);
    	cout<<endl<<"Enter some characters in string b "<<endl;
    	gets(b);
    	int i=0, check=0;
    	while (a[i] != '\0')
    	{
    		count++;
    		i++;
    	} //end while
    	cout<<endl<<"There are "<<count<<" characters in string a";
    	for(int j=0; j<=count; j++)
    	{
    		if (a[j]==b[j])
    		{	check=1; }
    	} //end for
    	cout<<endl<<"The value for check is "<<check;
    	getch();
    	return 0;
    }
    Pastebin

    I can't understand why the value for check is always 1, even if the two strings are totally different.
    Test case:
    string a = abc
    string b = def
    value for check = 1

    If anyone could help me understand :)
     
  2. qrazy

    qrazy Senior Member

    Joined:
    Mar 19, 2012
    Messages:
    1,111
    Likes Received:
    1,712
    Location:
    Banana Republic
    It's because both your string contains "null termination character" ('\0') at the end and satisfies your condition in the loop when it reaches the end of the array, so it's always true. You should always try to use string library functions like strcmp for string operations.
     
    • Thanks Thanks x 1
Thread Status:
Not open for further replies.