A little C++ question

Status
Not open for further replies.

bk071

Elite Member
Joined
Nov 24, 2010
Messages
3,302
Reaction score
8,845
---- 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 :)
 
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.
 
Status
Not open for further replies.
Back
Top