I cannot assign values to dynamic cstring and modfiy them - c++

For a homework problem, I need to implement a cstring class and overload operators. However, I am having trouble initializing the char array. In the following code,
StringClass::StringClass()
{
c = new char[10];
c = "Default";
stringlength = strlen(c);
}
#pragma once
#include <fstream>
class StringClass
{
private:
char* c;
int stringlength;
public:
StringClass();
~StringClass();
void print()const;
StringClass(char*, int);
StringClass(const StringClass*);
StringClass& operator=(const StringClass*);
friend std::istream& operator>>(std::istream&, StringClass*);
friend std::ostream& operator<<(std::ostream&, const StringClass*);
StringClass& operator+(const StringClass*);
char operator[](int);
};
For the line c = "Default";
I get an error const char* cannot be assigned to char*,but I did not set c to a const. If I change charc to const char c, I can set it equal to default in the constructor but then I cannot modify it further. Why is this?
EDIT: I can change the declaration to this and it works properly. Is this the correct way to do this?
c = new char[10]{ "Default" };
Full implementation file,
#include "StringClass.h"
#include <fstream>
#include <iostream>
StringClass::StringClass()
{
c = new char[10];
c = "Default";
stringlength = strlen(c);
}
StringClass::~StringClass()
{
c = NULL;
delete c;
}
void StringClass::print()const
{
for (int i = 0; i < 10; ++i)
std::cout << c[i];
std::cout<< std::endl;
std::cout << stringlength;
}
StringClass::StringClass(const StringClass* p)
{
for (int i = 0; i < 10; ++i)
{
c[i] = p->c[i];
}
stringlength = p->stringlength;
}
StringClass& StringClass::operator=(const StringClass* a)
{
if (this == a)
return *this;
else
{
for(int i = 0; i < 10; ++i)
c = &a->c[i];
stringlength = a->stringlength;
}
return *this;
}
//std::istream& operator>>(std::istream& in, StringClass* a)
//{
//in >> a->c >> a->stringlength;
//return in;
//}
std::ostream& operator<<(std::ostream& out, const StringClass* a)
{
out << a->c << " " << a->stringlength << std::endl;
return out;
}
StringClass& StringClass::operator+(const StringClass* a)
{
StringClass temp;
temp.c = c + *a->c;
temp.stringlength = stringlength + a->stringlength;
return temp;
}
char StringClass::operator[](int a)
{
return c[a];
}

c = new char[10]{ "Hello" };

Related

Trouble with operator << in class StringSet

I am defining my own string class called StringSet using a vector of strings. I am assigned to overload the >>, <<, ==, >, >=, +, += and * operators, and ran into a problem with <<. The output should be:
Welcome to stringset
hi everyone
"all" does not exist in the set.
hi
But it seems to be skipping the second and third lines. I am very new to overloading operators, so I am probably overlooking an obvious mistake.
header and class declaration:
#include <iostream>
#include <vector>
#include<string>
#include <iterator>
#include <algorithm>
#include <fstream>
using namespace std;
class StringSet
{
public:
//Constructor
StringSet();
//Copy Constructor
StringSet(const StringSet& s);
//Default constructors
StringSet(string initialStrings[], const int ARRAYSIZE);
//Destructor
~StringSet();
void add(const string s);
void remove(const string s);
//Returns length
int size()
{
return length;
}
// Overload the << operator so that it outputs the strings
friend ostream& operator <<(ostream& outs, const StringSet& s);
private:
//size of the vector
int length;
// Vector to store strings
vector <string> data;
};
function definitions:
ostream& operator<<(ostream& outs, const StringSet& s)
{
outs << "\n";
for (int i = 0; i < s.length; i++)
{
outs << s.data[i] << " ";
}
outs << "\n";
return outs;
}
//Add a string to the vector
void StringSet::add(const string s)
{
bool c = check(s);
if (c == false)
{
data.push_back(s);
}
else
{
cout << "\"" << s << "\" already exists in the set.";
}
}
// Remove a string from the vector
void StringSet::remove(const string s)
{
bool c = check(s);
if (c == true)
{
vector<string>::iterator position = search(s);
data.erase(position);
}
else
{
cout << "\"" << s << "\" does not exist in the set\n";
}
}
StringSet::StringSet()
{
length = 0;
}
StringSet::StringSet(string initialStrings[], const int ARRAYSIZE)
{
for (int i = 0; i < data.size(); i++)
{
initialStrings[i] = " ";
}
}
// Copy constructor
StringSet::StringSet(const StringSet& s)
{
for (int i = 0; i < data.size(); i++)
{
data[i] = s.data[i];
}
}
StringSet::StringSet()
{
length = 0;
}
StringSet::StringSet(string initialStrings[], const int ARRAYSIZE)
{
for (int i = 0; i < data.size(); i++)
{
initialStrings[i] = " ";
}
}
// Copy constructor
StringSet::StringSet(const StringSet& s)
{
for (int i = 0; i < data.size(); i++)
{
data[i] = s.data[i];
}
}
// Check if a string exists in the vector
bool StringSet::check(const string s)
{
vector<string>::iterator it = find(data.begin(), data.end(), s);
if (it != data.end())
{
return true;
}
else
{
return false;
}
}
Main function:
int main()
{
ofstream outs;
ifstream ins;
StringSet doc1, doc2, query
cout << "Welcome to stringset\n";
doc1.add("hi");
doc1.add("everyone");
outs << doc1;
doc1.remove("everyone");
doc1.remove("all");
outs << doc1;
}
If you use a variable that stores the size of the set, you should increment/decrement it when adding/removing elements. You can also change the definition of the StringSet::size():
int size() const
{
return static_cast<int>(data.size());
}

Copy Constructor for dynamically allocated array

Trying to familiarize myself with the "Rule of 3" and Im having trouble getting a Copy Constructor to work. One of the class private members is returning 0 when it should have a value of 3.
Im not sure as to why when the Copy Constructor function is performed, a value of 0 is supplied to that classes private member. The member in question is theSize which is returned via the size() function in class.cpp.
class.h
class Catalog {
public:
Catalog (int maxCapacity = 100)
int size() const;
int capacity() const;
void add (Book b);
Catalog(const Catalog& c);
~Catalog();
Catalog& operator= (constCatalog& c) {
if (this != &c) {
delete[] books;
books = new Book[theCapacity];
*books = *(c.books);
}
return *this;
}
private:
Book* books;
int theCapacity;
int theSize;
};
class.cpp
Catalog::Catalog(int maxCapacity) {
theCapacity = maxCapacity;
theSize = 0;
books = new Book[theCapacity];
}
int Catalog::size() const {
return theSize();
}
int Catalog::capacity() const {
return theCapacity;
}
void Catalog::add (Book b)
{
if (theSize < theCapacity || contains(b.getID())) {
if (theSize == 0) {
books[0] = b;
theSize++;
}
else {
if (!contains(b.getID())) {
int i = theSize;
for (; i && b < books[i-1]; --i) {
books[i] = books[i - 1];
}
books[i] = b;
for (; i; --i) {
books[i - 1] = books[i - 1];
}
theSize++;
}
else {
for (int i = 0; i < theSize; ++i) {
if (b == books[i]) {
books[i] = b;
}
}
}
}
// Debugging only
/*for (int i = 0; i < theSize; i++) {
//cout << books[i] << endl;
}*/
}
}
bool Catalog::contains(std::string bookID) const
{
for (int i = 0; i < theSize; ++i)
{
if (books[i].getID() == bookID)
return true;
}
return false;
}
Catalog::Catalog(const Catalog& c) {
books = new Book[c.theSize];
for (int i = 0; i < c.theSize; i++) {
books[i] = c.books[i];
}
Catalog::~Catalog() {
delete[] books;
}
Later in main.cpp when I call c1.size() where c1 is the result of return c in another function that through use of the debugger comes from the Copy Constructor and then goes to the Destructor. However, c1.size() is returning as 0 though the Copy Constructor theSize = c.size() has a value of 3 when stepped through.
book.cpp
using namespace std;
/**
* Create a book.
*
* #param id the Gutenberg ID for this book
* #param authorInfo the author of the book
* #param title the title of the book
*/
Book::Book (std::string theId, std::string authorInfo, std::string theTitle)
: id(theId), authorName(authorInfo), title(theTitle)
{
}
bool Book::operator< (const Book& b) const
{
return id < b.id;
}
bool Book::operator== (const Book& b) const
{
return (id == b.id);
}
std::ostream& operator<< (std::ostream& out, const Book& b)
{
cout << b.getID() << "\t"
<< b.getAuthor() << "\t"
<< b.getTitle();
return out;
}
std::istream& operator>> (std::istream& in, Book& b)
{
string line;
getline (in, line);
if (!in.good())
return in;
int tab1 = line.find ("\t");
int tab2 = line.find ("\t", tab1+1);
string id = line.substr(0, tab1);
string author = line.substr (tab1+1, tab2-tab1-1);
string title = line.substr(tab2+1);
b.setID (id);
b.setAuthor (author);
b.setTitle (title);
return in;
}
main.cpp
using namespace std;
Catalog readCatalog(const string& fileName)
{
Catalog c;
ifstream in (fileName);
in >> c;
in.close();
return c;
}
Catalog mergeCatalogs (const Catalog& cat1, const Catalog& cat2)
{
Catalog result (cat1.size() + cat2.size());
int i = 0;
int j = 0;
while (i < cat1.size() && j < cat2.size())
{
Book b1 = cat1.get(i);
Book b2 = cat2.get(j);
if (b1.getID() < b2.getID())
{
result.add(b1);
++i;
}
else
{
result.add(b2);
++j;
}
}
while (i < cat1.size())
{
result.add(cat1.get(i));
++i;
}
while (j < cat2.size())
{
result.add(cat2.get(j));
++j;
}
return result;
}
void mergeCatalogFiles (const string& catalogFile1, const string& catalogFile2)
{
Catalog c1, c2;
c1 = readCatalog(catalogFile1);
cout << catalogFile1 << " contained " << c1.size() << " books." << endl;
c2 = readCatalog(catalogFile2);
cout << catalogFile2 << " contained " << c2.size() << " books." << endl;
Catalog c3 = mergeCatalogs (c1, c2);
cout << "Their merge contains " << c3.size() << " books." << endl;
cout << c3 << flush;
}
int main (int argc, char** argv)
{
if (argc != 3)
{
cerr << "Usage: " << argv[0] <<
"catalogFile1 catalogFile2" << endl;
return -1;
}
string file1 = argv[1];
string file2 = argv[2];
mergeCatalogFiles (file1, file2);
if (Counted::getCurrentCount() == 0)
{
cout << "No memory leak detected." << endl;
return 0;
}
else
{
cout << "Memory leak detected: " << Counted::getCurrentCount() << endl;
return -2;
}
}
Follow rule of zero: use std::vector<Book> to replace the array pointer and the size.
Your capacity is a limit on the size.
When at capacity. use equal range to find where to insert, replace last element then std rotate.
Managing both resources and business logic in the same class is bug prone. Do one thing at a time.
Try something more like this instead:
class Catalog
{
public:
Catalog (int maxCapacity = 100);
Catalog(const Catalog& c);
~Catalog();
int size() const;
int capacity() const;
void add (const Book &b);
Book* find(const std::string &bookID) const;
Catalog& operator= (Catalog c);
private:
Book* books;
int theCapacity;
int theSize;
void swap(Catalog &c);
};
#include "class.h"
#include <algorithm>
Catalog::Catalog(int maxCapacity)
{
theCapacity = maxCapacity;
theSize = 0;
books = new Book[theCapacity];
}
Catalog::Catalog(const Catalog& c)
{
theCapacity = c.theCapacity;
books = new Book[theCapacity];
for(int i = 0; i < c.theSize;; ++i)
books[i] = c.books[i];
theSize = c.theSize;
}
Catalog::~Catalog()
{
delete[] books;
}
Catalog& Catalog::operator= (const Catalog &c)
{
if (this != &c)
Catalog(c).swap(*this);
return *this;
}
void Catalog::swap(Catalog &c)
{
std::swap(books, c.books);
std::swap(theSize, c.theSize);
std::swap(theCapacity, c.theCapacity);
}
int Catalog::size() const
{
return theSize;
}
int Catalog::capacity() const
{
return theCapacity;
}
void Catalog::add (const Book &b)
{
Book *book = find(b.getID());
if (book) {
*book = b;
}
else if (theSize < theCapacity)
{
int i;
for (i = theSize; i && b < books[i-1]; --i) {
books[i] = books[i - 1];
}
books[i] = b;
++theSize;
}
// Debugging only
/*
for (int i = 0; i < theSize; ++i) {
cout << books[i] << endl;
}
*/
}
Book* Catalog::find(const std::string &bookID) const
{
for (int i = 0; i < theSize; ++i)
{
if (books[i].getID() == bookID)
return &books[i];
}
return 0;
}
That being said, this would be much simpler and easier to manage if you use std::vector and STL algorithms. Let the STL do the hard work for you:
#include <vector>
class Catalog
{
public:
Catalog (int initialCapacity = 100);
int size() const;
int capacity() const;
void add (const Book &b);
Book* find(const std::string &bookID) const;
private:
std::vector<Book> books;
};
#include "class.h"
#include <algorithm>
Catalog::Catalog(int initialCapacity)
{
books.reserve(initialCapacity);
}
int Catalog::size() const
{
return books.size();
}
int Catalog::capacity() const
{
return books.capacity();
}
void Catalog::add (const Book &b)
{
Book *book = find(b.getID());
if (book) {
*book = b;
}
else {
books.insert(std::upper_bound(books.begin(), books.end(), b), b);
}
// Debugging only
/*
for (Book &book: books) {
cout << book << endl;
}
*/
}
Book* Catalog::find(const std::string &bookID) const
{
auto iter = std::find_if(books.begin(), books.end(), [&bookID](const Book &b){ return (b.getID() == bookID); });
if (iter != books.end())
return &*iter;
return 0;
}

Overload operator>> in self-made class 'String' C++

I am creating class 'String'.
But I have a problem with overloading of operator>>.
I've tried to do like this:
istream& operator >> (istream& input, String& inputStr)
{
char str[] = "";
input >> str;
inputStr.size = strlen(str);
inputStr.str = new char[inputStr.size];
for (int i = 0; i < inputStr.size; i++)
{
inputStr.str[i] = str[i];
}
return input;
}
But it doesn't work =(
Can you help me to overload this operator ?
Here is a code:
#pragma once
#include<iostream>
using namespace std;
class String
{
private:
int size;
char* str;
public:
String();
~String();
String(char* arr);
String(const String& copy);
int sizeStr();
friend ostream& operator << (ostream& output, const String& outputStr);
friend istream& operator >> (istream& input, String& inputStr);
};
String::String()
{
this->size = 0;
this->str = nullptr;
}
String::String(char* str)
{
this->size = strlen(str);
this->str = new char[size];
for (int i = 0; i < size; i++)
{
this->str[i] = str[i];
}
}
String::~String()
{
delete[] str;
}
String::String(const String& copy)
{
if (this != &copy)
{
this->size = copy.size;
this->str = new char[size];
for (int i = 0; i < size; i++)
{
this->str[i] = copy.str[i];
}
}
}
int String::sizeStr()
{
return this->size;
}
ostream& operator << (ostream& output, const String& outputStr)
{
for (int i = 0; i < outputStr.size; i++)
{
output << outputStr.str[i];
}
return output;
}
istream& operator >> (istream& input, String& inputStr)
{
return input;
}
I`m looking forward to your help.

Apply operator overriding to classes with dynamic allocation pointers

I have defined the MyString class, and now I want to implement the addition operation. It's horrible for memory leaks to occur, so I've taken care of releasing the dynamically allocated pointers from the destructor.
#include <iostream>
class MyString {
private:
int _size;
char* _str;
public:
MyString() {
_size = 0;
_str = nullptr;
}
MyString(int size, char* str) {
_size = size;
_str = new char[size + 1];
strcpy(_str, str);
}
~MyString() {
delete[] _str;
}
void print() {
std::cout << _str << std::endl;
}
friend MyString operator+(const MyString& lhs, const MyString& rhs);
};
MyString operator+(const MyString& lhs, const MyString& rhs) {
char* temp = new char[lhs._size + rhs._size + 1];
strcpy(temp, lhs._str);
strcat(temp, rhs._str);
MyString ret(lhs._size + rhs._size, temp);
delete[] temp;
return ret;
}
int main() {
MyString first(5, "first");
MyString second(6, "second");
MyString add = first + second;
first.print();
second.print();
add.print();
}
However, if I compile the code and run it, the first.print() and second.print() is printed well, but the add.print() will print the garbage value, and crashes (Debug Assertion Failed!).
Output:
first
second
硼硼硼硼硼硼硼硼?흚 (and creashes :(.. )
If I annotate and run the destructor, it prints well, but a memory leak occurs. Why is this happening? I have looked at several examples of operator overriding, but I have not found an example of this dynamic allocation of pointers.
Any suggestion will be highly appreciated!
MyString operator+(const MyString& lhs, const MyString& rhs) {
char* temp = new char[lhs._size + rhs._size + 1];
strcpy(temp, lhs._str);
strcat(temp, rhs._str);
MyString ret(lhs._size + rhs._size, temp);
delete[] temp;
return ret;
}
At the end of this function 'ret' is destroyed which calls the destructor and deletes the buffer. What is returned is a new instance of MyString that was copied from 'ret', and its buffer points to the same memory location as the original. Since this has been deleted you are now printing out garbage.
To fix this you can add a copy constructor to ensure the buffer is copied:
class MyString {
// Other class details
public:
MyString(const MyString & other) : MyString(other._size, other._str) {}
// Other class details
}
This will ensure the buffer is copied when one MyString is assigned to another MyString.
#include<iostream>
using namespace std;
class Mystring{
private:
int size;
char *str;
public:
friend Mystring operator*(const Mystring &a, const int &d);
friend Mystring operator+(const Mystring &a, const Mystring& b);
friend ostream& operator << (ostream &os, const Mystring a);
friend istream& operator >> (istream &is, const Mystring a);
Mystring (int a, char b) {
this->size = a;
this->str = new char(a);
for (int i = 0; i < a; i++) {
this->str[i] = b;
}
}
~Mystring() {}
};
Mystring operator+(const Mystring &a, const Mystring& b) {
Mystring c(a.size + b.size, { 0 });
for (int i = 0; i < a.size; i++)
{
c.str[i] = a.str[i];
}
for (int i = 0; i < b.size; i++)
{
c.str[a.size + i] = b.str[i];
}
return c;
}
Mystring operator*(const Mystring& a,const int &d){
int z = a.size*d;
Mystring c(z, { 0 });
int k=0;
for (int j = 0; j < d; j++)
{
for (int i = 0; i < a.size; i++)
{
c.str[k+i] = a.str[i];
}
k = a.size + k;
}
return c;
}
ostream& operator << (ostream &os, const Mystring a) {
os << "[";
int i;
for ( i = 0; i < a.size; i++)
{
os << a.str[i];
}
os << "]";
return os;
}
istream& operator >> (istream &is, const Mystring a) {
for (int i = 0; i < a.size; i++)
{
cout << i << "번째 문자 : ";
is >> a.str[i];
}
return is ;
}
int main()
{
int aSize, bSize, iter;
char aInit, bInit;
cout << "문자열A의 크기와 초기문자를 입력: ";
cin >> aSize >> aInit;
Mystring str1(aSize, aInit);
cout << str1 << endl;
cout << "문자열A 입력" << endl;
cin >> str1;
cout << str1 << endl;
cout << "문자열B의 크기와 초기문자를 입력: ";
cin >> bSize >> bInit;
Mystring str2(bSize, bInit);
cout << str2 << endl;
cout << "문자열B 입력" << endl;
cin >> str2;
cout << str2 << endl;
cout << "문자열A와 문자열B 합치기 : ";
Mystring str3 = str1 + str2;
cout << str3 << endl;
cout << "문자열A 반복횟수 입력 : ";
cin >> iter;
Mystring str4 = str1*iter;
cout << str4 << endl;
}
enter code here
why error
~Mystring(){}

C++, classes, Segmentation fault, all over the programme

I got an exercise form my teacher (the main() function) and was supposed to write functions and classes so that it would work. But I have seg fault and have no idea what to do about it. I would be grateful for any recommendations.
#include <iostream>
class TSeries{
public:
TSeries()
{
_size = 0;
_capacity = 0;
_tab = NULL;
}
TSeries(float *tab, const int size)
{
_tab = new float[size];
for(int i =0;i<size;i++) _tab[i] = tab[i];
_size = size;
}
~TSeries(){delete [] _tab;}
TSeries & operator+=(float value){return insert(value);}
TSeries & operator,(float value){return insert(value);}
TSeries & operator+(const TSeries & s)
{
// if(this->_size != s._size) std::cout<<"Size doesn't match!"<<std::endl;
/*else
{
std::cout<<"whee";
for(int i; i<this->_size;i++)
{
//this->_tab[i] += s._tab[i];
std::cout<<"nothing";
}
return *this;
}*/
std::cout<<"sth";
}
TSeries & operator()(int position1, int position2){}
TSeries & insert(float k)
{
if(_size >= _capacity) Enlarge();
_tab[_size++] = k;
return *this;
}
friend std::ostream & operator<<(std::ostream & out, const TSeries & s);
private:
int _size, _capacity;
float *_tab, *_itr;
static int _nr;
void Enlarge()
{
_capacity = 2 * _capacity + 1;
float *tmp = new float[_capacity];
for( int i=0;i<_size;++i)
{
tmp[i] = _tab[i];
}
delete [] _tab;
_tab = tmp;
}
};
std::ostream & operator<<(std::ostream & out, const TSeries & s)
{
int przedostatni = s._size - 1;
out<<"(";
for(int i =0;i<s._size;i++)
{
out<<(int)s._tab[i];
if(i != przedostatni)
out<<",";
}
out<<")"<<std::endl;
}
using namespace std;
int main(int argc, char **argv) {
TSeries series1;
series1 += 1.,2.,4.,2.;
cout<<"Series1: "<<series1<<endl;
const int size=7;
float tab[size] = {3.,3.,3.,4.,5.,1.,0.};
const TSeries series2(tab,size);
cout<<"Series2: "<<series2<<endl<<endl;
TSeries series3 = series1+series2;
cout<<"Series3: "<<series3<<endl<<endl;
series1+=1.,0.,3.;
series3=series1+series2;
cout<<" "<<series1<<endl;
cout<<" +"<<series2<<endl;
cout<<" ---------------------"<<endl;
cout<<"Series3: "<<series3<<endl<<endl;
//TSeries series4=series1(2,4);
cout<<"Series4: "<<series3<<endl;
return 0;
}
You fixed one of your problems (the assignment to the _tab pointer).
The other problem should have caused a warning from the compiler.
You need to return out from your operator<< method.
Note that you also should use the out parameter, rather than always using cout in the the method.