#include <iostream>
#include <string>
using namespace std;
class String {
public:
String (){
//default
value = 0;
name = "noname";
}
String (int x){
setValue(x);
}
String (string y){
setName(y);
}
String (int x ,string y) {
setValue(x);
setName(y);
}
void setValue(int x){
value = x;
}
void setName(string y){
name = y;
}
int getValue(){
return value;
}
string getName(){
return name;
}
int Compare (const char* name1,const char* name2){
const char* n1 = name1;
const char* n2 = name2;
if (strcmp(n1, n2) != 0)
cout <<"test"<<endl;
};
private:
int value;
string name;
const char* n1;
const char* n2;
};
int main ()
{
string str1 ("abcd");
string str2 ("bbbb");
int Compare("abcd", "bbbb");
//String coin1(1,"Penny");
//cout<<"Coin 1 is a "<<coin1.getName()<<" and its worth $"<<coin1.getValue()<<endl;
//String coin2(10,"Dime");
//cout<<"Coin 2 is a "<<coin2.getName()<<" and its worth $"<<coin2.getValue()<<endl;
return 0;
}
I am probably going about this completely wrong but I can't think of any way else to do it.I'm trying to make a strcmp that allows the comparison of the String object to another String object or to a “C” type string but I seem to be doing it wrong.
Because you're not instantiating your String
object.
Try with the following main()
int main ()
{
String str1 ("abcd"); // create an instance of String class
String str2 ("bbbb"); // create another
printf("%i", str1.Compare("abcd", "bbbb"));
printf("%i", str2.Compare("abcd", "bbbb"));
return 0;
}
You can also make your Compare()
method to work with the instanced string instead, so:
int Compare (const char* nameOther)
{
const char* n1 = name.c_str();
const char* n2 = nameOther;
int result = strcmp(n1, n2);
if (result != 0)
cout <<"not equal"<<endl;
else
cout <<"equal"<<endl;
return result; // you forgot the 'return' at Compare().
};
Then you can do:
int main ()
{
String str1 ("abcd"); // create an instance of String class
String str2 ("bbbb"); // create another
printf("%i", str1.Compare("abcd"));
printf("%i", str2.Compare("abcd"));
return 0;
}
After you tested it, you can remove the unnecessary code from Compare():
int Compare (const char* nameOther)
{
return strcmp(name.c_str(), nameOther);
};