I am trying to change the default value in a print function so that n > len, however, when I do so, the output has garbage at the end of it. How do I properly get rid of the extra characters?
#include <iostream>
#include <assert.h>
#include <cstring>
using std::cout;
using std::endl;
class my_string
{
public:
my_string();
my_string(const my_string& str);
my_string(const char* p);
~my_string();
int strcmp(const my_string& s1);
void strrev();
void print(int n = 0)const;
int const Len();
const char* gStr();
private:
char* s;
int len;
};
my_string::my_string(): len(0),s (0){}
my_string::my_string(const char* p)
{
len = strlen (p);
s = new char[len + 1];
assert(s != 0);
strcpy(s, p);
}
my_string::my_string(const my_string& str):len(str.len)
{
s = new char[len + 1];
assert(s != 0);
strcpy(s, str.s);
}
// Destructor
my_string::~my_string()
{
delete [] s;
}
int const my_string::Len()
{
return len;
}
const char* my_string::gStr()
{
return s;
}
int main ()
{
my_string string1("alibi");
string1.print();
string1.print(-1);
string1.print(3);
string1.print(23);
cout << "\n" << endl;
my_string comp1("gladiator");
if (comp1.strcmp ("gladiolus") < 0)
cout << comp1.gStr() << " < " << "gladiolus" << endl;
else if (comp1.strcmp ("gladiolus") == 0)
cout << comp1.gStr() << " = " << "gladiolus" << endl;
else
cout << comp1.gStr() << " > " << "gladiolus" << endl;
cout << "Original String: " << comp1.gStr() << " \nReversed String: ";
comp1.strrev();
comp1.print();
cout << "\n" << endl;
my_string comp2("xyz");
if (comp2.strcmp ("abcd") < 0)
cout << comp2.gStr() << " < " << "abcd" << endl;
else if (comp2.strcmp ("abcd") == 0)
cout << comp2.gStr() << " = " << "abcd" << endl;
else
cout << comp2.gStr() << " > " << "abcd" << endl;
cout << "Original String: " << comp2.gStr() << " \nReversed String: ";
comp2.strrev();
comp2.print();
cout << "\n" << endl;
my_string comp3("same");
if (comp3.strcmp ("same") < 0)
cout << comp3.gStr() << " < " << "same" << endl;
else if (comp3.strcmp ("same") == 0)
cout << comp3.gStr() << " = " << "same" << endl;
else
cout << comp3.gStr() << " > " << "same" << endl;
cout << "Original String: " << comp3.gStr() << " \nReversed String: ";
comp3.strrev();
comp3.print();
cout << "\n" << endl;
system("PAUSE");
}
//Function that compares characters in a string
int my_string::strcmp(const my_string& s1)
{
int i=0;
while(s1.s[i] && s[i] && s1.s[i] == s[i])
{
i++;
}
return s1.s[i]-s[i];
}
//Function that reverses a given string
void my_string::strrev()
{
char* temp = new char[len + 1];
int i = len -1;
int j= 0;
while (s[i])
{
temp[j++] = s[i--];
}
temp[j] ='\0';
strcpy(s,temp);
delete[] temp;
}
//Funtion that prints a string
void my_string::print(int n)const
{
if (n < 0 || n > len)
cout << "String Length Error!";
else if (n == 0)
n = len;
for (int i = 0; i < n; i++)
cout << s[i];
cout << endl;
}