Mar 18, 2011 at 11:48am Mar 18, 2011 at 11:48am UTC
Dear Friends,
I need help to understand why junk character are displayed.
Read the following code. I have created a user defined datatype MyString.
It has two constructors; one is default and other takes a constant value.
I have also defined a function to concatenate two strings.
#include <conio.h>
#include <stdio.h>
#include <string.h>
#include <iostream.h>
//const int max = 100;
class mystring
{
char *str;
unsigned int lenstr;
public:
mystring()
{
str = new char[1];
str[0] = '\0';
lenstr = 0;
//cout << "Unintialized String Object " << str << endl;
}
mystring(char *temp);
void addstring(mystring &tempobj1, mystring &tempobj2);
void display();
~mystring()
{
delete [] str;
}
};
void mystring :: display()
{
cout << str << " Len: " << lenstr <<endl;
}
mystring :: mystring(char *temp)
{
int i=0, cnt=0;
while(temp[i] != '\0')
{
cnt++;
i++;
}
str = new char[cnt];
for (int j=0; j<cnt; j++)
{
str[j] = temp[j];
}
str[cnt] = '\0';
lenstr = cnt;
}
void mystring :: addstring(mystring &tempobj1, mystring &tempobj2)
{
str = tempobj1.str;
int i=0, temp = tempobj1.lenstr;
while (tempobj2.str[i]!='\0')
{
str[temp+i] = tempobj2.str[i];
i++;
}
str[temp+i] = '\0';
lenstr = temp+i;
//cout << endl << lenstr << endl;
//display();
}
void main()
{
clrscr();
mystring s1, s2("London"), s3(" United Kingdom."), s4;
cout << "Empty String: ";
s1.display();
cout << "Constant String: ";
s2.display();
cout << "Constant String: ";
s3.display();
cout << "Concatenate String: ";
s4.addstring(s2,s3);
s4.display();
getch();
}
OutPut:
Empty String: Len: 0
Constant String: London§ Len: 6
Constant String: United Kingdom. Len: 16
Concatenate String: London United Kingdom. Len: 23
Thanks.
Last edited on Mar 18, 2011 at 11:51am Mar 18, 2011 at 11:51am UTC
Mar 18, 2011 at 4:18pm Mar 18, 2011 at 4:18pm UTC
iostream.h ? What compiler do you use ? One more than 10 years old ?
Last edited on Mar 18, 2011 at 4:18pm Mar 18, 2011 at 4:18pm UTC
Mar 18, 2011 at 4:30pm Mar 18, 2011 at 4:30pm UTC
Im using turbo C++ 3.0 complier from borland
Mar 18, 2011 at 4:32pm Mar 18, 2011 at 4:32pm UTC
Wikipedia says Turbo C++ 3.0 is from 1991!
Mar 18, 2011 at 4:38pm Mar 18, 2011 at 4:38pm UTC
gr8.. can u plz help me..
Mar 18, 2011 at 4:40pm Mar 18, 2011 at 4:40pm UTC
Yes. Get Code Blocks or MS VC++ Express. They're free to download and come with updated compilers.
Mar 18, 2011 at 4:43pm Mar 18, 2011 at 4:43pm UTC
does that mean my code is right...
Mar 18, 2011 at 6:23pm Mar 18, 2011 at 6:23pm UTC
@filipe: Im sorry about the unindented code. im new to this. il remember it next time.
@Grey wolf: In my college we are still using c++ borland compiler. i tried switching to vc++ but i got some lib error. cudnt resolved it so switched back to borland. I have my semester in a months time. dont have time for RnD.
Thanks..
Last edited on Mar 19, 2011 at 6:03am Mar 19, 2011 at 6:03am UTC