Dec 19, 2012 at 11:31am UTC
hi
i want to change this code from char type to string type, is it possible? i put this '===>' where VC is giving error indication.
#include <iostream>
using namespace std;
#include <string.h> //for strcpy(), strcat()
#include <stdlib.h> //for exit()
////////////////////////////////////////////////////////////////
class Strings //user-defined string type
{
private:
//enum { SZ=80 }; //size of String objects
//char str[SZ]; //holds a string
string str;
public:
Strings() //constructor, no args
{ };
Strings( string s) //constructor, one arg
{ str = s; }
void display() const //display the String ========> this line has a problem
{ cout << str; }
Strings operator + (Strings ss) const //add Strings
{
Strings temp; //make a temporary String
//if( strlen(str) + strlen(ss.str) < SZ )
{
temp.str= str; //copy this string to temp
strcat(temp.str , ss.str); //add the argument string======> And this line is problem
}
//else
//{ cout << "\nString overflow"; exit(1); }
return temp; //return temp String
}
};
////////////////////////////////////////////////////////////////
int main()
{
Strings s1 = "\nMerry Christmas! "; //uses constructor 2
Strings s2 = "Happy new year!"; //uses constructor 2
Strings s3; //uses constructor 1
s1.display(); //display strings
s2.display();
s3.display();
s3 = s1 + s2; //add s2 to s1,
//assign to s3
s3.display(); //display s3
cout << endl;
return 0;
}
Dec 19, 2012 at 11:44am UTC
You forgot to #include <string>
, which is not the same as #include <string.h>
(and which is #include <cstring>
in modern C++.)
Last edited on Dec 19, 2012 at 11:44am UTC
Dec 20, 2012 at 5:16am UTC
hi
I added that cstring but it still give an error :(.
Dec 20, 2012 at 7:50am UTC
@JLBorges
Can i use here string type rather then char *?
Strings( const char* cstr ) : str(cstr) {}
like
Strings( const string cstr ) : str(cstr) {}
Last edited on Dec 20, 2012 at 7:51am UTC
Dec 20, 2012 at 7:56am UTC
> Can i use here string type rather then char *?
Since std::string has a copy constructor, the implementation will synthesise such a (copy) constructor -
Strings( const Strings& ) ;
You need the constructor which takes a const char *
,
or else this code will not compile:
Strings s1 = "\nMerry Christmas! " ; // construct Strings s1 from a const char*
Dec 20, 2012 at 8:25am UTC
@JLBorges
thanks alot
btw Whatis the purpose of this line here
Strings( const char* cstr ) : str(cstr) {}
regards,
Dec 20, 2012 at 8:43am UTC
Last edited on Dec 20, 2012 at 8:43am UTC
Dec 20, 2012 at 11:29am UTC
@JLBorges
I mean if i remove that line i am still able to play with string so is this necessary?
thanks
Dec 21, 2012 at 4:44am UTC
thanks man for support!
Regards