-
if block always false.
part of my code
Code:
#include <iostream>
#include <algorithm>
#include <string>
#include <fstream>
using namespace std;
int main () {
int x;
int y;
char a[]={};
char b[]={};
ifstream word("test1.txt");
word>>a;
sort(a,a+strlen(a));
ifstream wordlist("text2.txt");
wordlist>>b;
sort(b,b+strlen(b));
cout<< a<<"="<<b;
if (a==b)
{cout<<"hello";} //print if equal
cin.get();
}
problem:
if block is always false.
i need char value for sort command.
-
I guess it should be
Code:
if(a[0] == b[0])
{
.....
.....
}
cin.get();
return 0;
-
You cant compare strings like that in C++. Maybe use strcmp(). IE:
Code:
if(! strcmp(a, b))
{
cout<<"hello";
}
[edit] The reason your code is allways false is because you are comparing two memory addresses, which will always be different.[/edit]
-
In the context of that if test, the code is comparing the address' of the two arrays in memory which will always be false. Also, your code to read the values from the user is wrong, your arrays are size 0, my compiler doesn't even allow me to do that (error C2466: cannot allocate an array of constant size 0). You've included the string header, are you hesitant to use it for some reason?
-
Better yet, just use C++ strings, which both allow that type of comparison and also grow dynamically. The OP is using C-style strings without allocating enough space (none, actually) for them.
-
Yes. The pointer to a and pointer to b are not likely to ever be equal, as there is no such thing as zero-length arrays. You haven't specified an array length, so I guess that b is one more than a, as the "default" size of a unsized array is 1.
This also means that you are most likely overflowing your array when you enter anything on your input, as one char is occupied by the end of string marker.
So, declare a[100], b[100] or some such to make them have a size and use strcmp() to compare, or use C++ string types.
--
Mats
-