-
char/string hierarchy...
i need my program to use greater-than (>) and less-than (<) IF/ELSE statements for char arrays or strings. but so far, it wont work, even though my professor demonstrated it with confidence. i am using the <string> header and i tried <cstring> but that only complicated things.
is it possible to compare the values of strings without converting every character to an int value? is there anything that can be done? :confused:
-
Code:
#include <string>
#include <iostream>
int main()
{
std::string str1 = "Apple";
std::string str2 = "Pear";
if( str1 < str2 )
std::cout << str1 << " is less than " << str2 << std::endl;
else if( str2 < str1 )
std::cout << str2 << " is less than " << str1 << std::endl;
else
std::cout << str1 << " is equal to " << str2 << std::endl;
return 0;
}
-
see, thats what i have been doing but it wont work. other people are telling me to use the <cstring> function strcmp(st1, st2) which will return 0, 1, and -1. if anyone has a better suggestion, i am all ears/eyes. :)
-
You have to tell us what won't work, why, etc. Are you using the string class or C style strings? If you are using the string class, hk_mp5kpdw's example should work. If you are using C style strings, then strcmp should work. If it is not, then it is because of how you implemented it or some other problem with information you haven't mentioned. Show us some code.
-
i got it working with the strcmp(x,y) function, but here is the code i was referring to earlier incase u wanted to see what i was talking about.
Code:
void insert(node *&p, char x[15])
{
if (p==NULL)
{
p=new(node);
strcpy(p->info, x);
p->left=NULL;
p->right=NULL;
}
else if(x < p->info)
{ cout<<"inserting p->LEFT";
insert(p->left, x);
}
else
{ cout<<"inserting p->RIGHT";
insert(p->right, x);
};
}
thanx for the help.... :)
-
To use hk_mp5kpdw's example, this function
Code:
void insert(node *&p, char x[15])
should take c++ style string as an argument like this
Code:
void insert(node *&p, string x)
and the rest of your code will work fine