So I'm trying to overload the += operator for a dictionary program assignment.
This is my function:
Definition& Definition::operator += (const String& input) {
String** temp;
temp = new String*[numDefs + 1];
temp[0] = new String[numDefs];
for (int i = 0; i < numDefs; i++) {
temp[i] = def[i];
}
temp[0][numDefs] = input;
delete[] def;
def = temp;
numDefs++;
return *this;
}
However when I try to put 'input' into 'temp' it doesn't seem to work. This is my String class function for allocating string to string:
String& String::operator=(const String& input) {
data = NULL;
(*this) = input.getData();
return *this;
}
and:
String& String::operator=(const char* input) {
if (data != input)
{
if (data != NULL)
{
delete[] data;
data = NULL;
}
data_len = strSize(input);
if (input != NULL)
{
data = new char[data_len + 1];
strCopy(data, input);
}
}
return *this;
}
Can't seem to find the problem.
There was an answer posted a minute ago that the user deleted and helped me, I changed the code to:
Definition& Definition::operator += (const String& input) {
String** temp;
int tempSize = numDefs + 1;
temp = new String*[tempSize];
for (int i = 0; i < numDefs; i++) {
temp[i] = new String;
temp[i] = def[i];
}
temp[numDefs] = new String;
(*temp[numDefs]) = input;
delete[] def;
def = temp;
numDefs = tempSize;
return *this;
}
Whoever it was, Thanks!
Related
So I've been trying to write string class for learning purposes, and when I tried to overload the + operator I got the strangest problem: The array I've been trying to crate had 4 extra spaces, no matter what amount I tried to create it with (Also the entire thing crashed horribly). So for example, when I wrote:
newStr.length = this->length + other.length;
newStr.str = new char[newStr.length+1];
newStr.str kept having 4 more spaces than this->length + other.length + 1, and when I just left it at newStr.str = new char[1], the array still have been created with 5 cells for some reason. I've tried to write the entire class without ever creating "int length" but that didn't work, nor did any my attempts to isolate the array creation from class(It works normally when not in class and not working with these specific class objects so it's not some visual studio bug). I've tried everything I could think of, though I'm new at this and most likely missed something. Could anybody please help me? Here's the entire code for reference, it's not that long:
#include <iostream>
#define DEBUG
using namespace std;
class MyString
{
private:
char* str;
int length;
public:
MyString()
{
str = nullptr;
length = 0;
}
MyString(const char *str)
{
length = strlen(str);
this->str = new char[length + 1];
for (int i = 0; i < length; i++)
{
this->str[i] = str[i];
}
this->str[length] = '\0';
}
~MyString()
{
delete[] str;
}
MyString& operator =(const MyString& other)
{
if (this->str != nullptr) delete[] str;
length = other.length;
this->str = new char[length + 1];
for (int i = 0; i < length; i++)
{
this->str[i] = other.str[i];
}
this->str[length] = '\0';
return *this;
}
MyString operator +(const MyString& other)
{
MyString newStr;
newStr.length = this->length + other.length;
newStr.str = new char[newStr.length+1];
for (int i = 0; i < this->length; i++)
{
newStr.str[i] = this->str[i];
}
for (int i = this->length; i < newStr.length; i++)
{
newStr.str[i] = other.str[i-strlen(this->str)];
}
newStr.str[newStr.length] = '\0';
return newStr;
}
void Print()
{
cout << str;
}
};
int main()
{
MyString a("TESTY");
MyString b("WUBBA");
a = a + b;
a.Print();
return 0;
}
I have a problem with my custom string operator += so that if I wanted to add a const char* to my custom string String, then it wouldn't add it, it would just be the String. I can get it to work with other custom String objects but not with c strings.
code in String.cpp
String::String(){
length =0;
capacity = 1024;
myStr = new char[0];
}
String::String (const String& s)
{
length = s.getLength();
myStr = new char[length];
for (unsigned j=0; j < length; j++){
myStr[j] = s[j];
}
}
String::String(char c){
length = 1;
myStr = new char(c);
}
String::String(const char* val){
if(val!= nullptr){
int counter = 0;
while(val[counter]!='\0')counter++; //Find length of the char array
length= counter;
myStr = new char[counter];
for(int i =0;i<counter;i++){
myStr[i]=val[i];
}
}else{
length = 1;
myStr = new char[length];
myStr[0] = '\0';
}
}
ostream& operator<< (std::ostream& os, const String& s)
{
os<<s.myStr;
return os;
}
istream& operator>> (std::istream& is, String& s)
{
char* c = new char[1000];
is >> c;
s = String(c);
delete[] c;
return is;
}
String::~String(){
delete[] myStr;
}
int String::getIndex(char getInd) const {
for(int i = 0;i<length;i++){
if(myStr[i]==getInd){
return i;
}
}
}
unsigned String::getLength() const{
return length;
}
String& String::operator+= (const String& s){
unsigned len = length+s.getLength();
char* str=new char[len];
for(int i = 0;i<length;i++){
str[i]=myStr[i];
}
for(int i = 0;i<s.length;i++){
str[length+1]=s[i];
}
delete myStr;
length = len;
myStr= str;
return *this;
}
String& String::operator+=(const char *c) {
unsigned l =0;
while(c[l] !='\0'){
l++;
}
unsigned len =length+l;//new length of new string
char* str = new char[len];
for(int i = 0;i<getLength();i++) {
str[i] = myStr[i];
}
for(int j = 0; j<l;j++){
str[len+j]=c[j];
}
delete myStr;
length = len;
myStr = str;
return *this;
}
String& String::operator=(const String& s){
if(this == &s){
return *this;
}
delete myStr;
length = s.getLength();
myStr = new char[length];
for(int i = 0;i<length;i++){
myStr[i]=s[i];
}
}
char& String::operator[](unsigned i){
if(i>=length) throw 1;
return myStr[i];
}
char String::operator[] (unsigned j) const
{
if (j >= length) throw 1;
return myStr[j];
}
Code in main.cpp
int main() {
char c[] = {'h','i'}
String add = "iscool";
String str="strworks";
str+=add;
str+=c;
cout<<str<<endl;
return 0;
}
The outcome for this program right now in the console is:
strworks
I am not sure what to change about the const char* c += operator function, i believe this is where the error is. I am also trying to use this string in a getline function but I try getline(file,String& s, ','); there is an error and I would appreciate any tips on how to implement the getline function with my new String class. The String str should be histrworks in the second line of output, however it is blank. I have already re written the logic of the += operator but it doesn't seem to be working. Let me know if there is any more information I need to give out that could assist you guys in finding the problem. The ultimate goal of this program is to read in a file of movie reviews and train an algorithim to find out if the review is positive/negative.
I need to assign one object to another object by overloading the "=" operator. Wrote code, but it doesn`t work. What could be the problem?
CString operator =(const CString& obj) {
CString temp;
temp.c = obj.c;
temp.length = obj.length;
return temp;
}
Full code:
#include <iostream>
using namespace std;
class CString {
private:
char* c;
int length;
public:
CString() {
length = 0;
c = new char[1];
*c = 0;
}
CString(const char* s) {
length = strlen(s);
c = new char[length + 1];
for (int i = 0; i < length; i++) { c[i] = s[i]; }
c[length] = '\0';
}
CString(int leng, char* payload) {
length = leng;
c = payload;
}
~CString() {
delete[] c;
}
CString operator +(const CString& b) {
int newlength = length + b.length;
char* newstr = new char[newlength + 1];
strcpy(newstr, c);
strcpy(newstr + length, b.c);
return CString(newlength, newstr);
}
void Show(void) { cout << c << endl; }
CString operator =(const CString& obj) {
CString temp;
temp.c = obj.c;
temp.length = obj.length;
return temp;
}
};
int main() {
CString a("First, ");
CString b("Second.");
a = c;
return 0;
}
First comment: as long as you specify the non-trivial destructor, and - even more imortant - the copy assignment, you need to specify the copy constructor as well.
Next, the copy operator shall return the reference to *this: this allows you to employ chaining like that: 'a = b = c;'
The copy-assignment may look like that:
CString& operator =(const CString& obj) {
delete[] c;
length = obj.length;
c = new char[length + 1];
for (int i = 0; i <= length; i++) { c[i] = obj.c[i]; }
return *this;
}
However, taking my first comment into consideration, you may implement the copying just once:
CString(const CString& obj) {
length = obj.length;
c = new char[length + 1];
for (int i = 0; i <= length; i++) { c[i] = obj.c[i]; }
}
CString& operator =(const CString& obj) {
CString tmp(obj)
swap(length, tmp.length);
swap(c, tmp.c);
return *this;
}
In addition your constructor CString(int leng, char* payload) looks suspicious. Do you realize that the c-string has to be allocated with new (and will be deleted in destructor)?
it's course's one of project and its goal is to make fully-worked MyString Class. Until made destructor method, it was worked well. but in main.cpp, when i tried to use these method i made, it occurs heap corruption. i thought the problem comes up from order of calling destructor but i couldn't figure out where it occurred.
try to check allocated memory(reverse called order)
processing without destructor method(it works)
main.cpp
void main() {
MyString a = MyString("HELLOMYNAMEIS");
char ab[10] = "thisiskrw";
MyString c = ab;
a = a + c;
cout << a;
}
MyString.cpp
MyString::~MyString() {
delete[] str_;
}
MyString operator+(const MyString& lhs, const MyString& rhs) {
MyString a(lhs);
MyString b(rhs);
a += b;
cout << a;
return a;
}
MyString& MyString::operator+=(const MyString& str) {
int i = 0;
if (this->capacity() < (this->length_ + str.length_)) {
char* temp = new char[this->length_ + str.length_+1];
memset(temp, '\0', this->length_+str.length_+1);
strcpy(temp, this->str_);
for (int i = 0; i < str.length_; i++) {
temp[(this->length_) + i] = str.str_[i];
}
temp[this->length_ + str.length_] = '\0';
strcpy(this->str_,temp);
this->length_ = this->length_ + str.length_;
delete[] temp;
}
else {
for (int i = 0; i < str.length_; i++) {
this->str_[(this->length_) + i] = str.str_[i];
}
this->length_ = this->length_ + str.length_;
}
return *this;
}
it will print string inside MyString object.
You forgot to write this->str_ = temp; anywhere. You just try to write the longer string into the shorter space.
strcpy(this->str_,temp);
this->length_ = this->length_ + str.length_;
delete[] temp;
Should be
delete [] this->str_;
this->str_ = temp;
I am implementing my version of the basic String class, however I am running into an issue that I have never seen before and have no idea how to properly debug. My code is pasted below. All functions have their header counterparts. My test is simply creating one object using the convert constructor.
A4String obj1("this");
My problem is I get an Access violation reading location exception thrown. My research has indicated that I may be trying to access memory outside of Visual Studio's allotment. I'm having trouble finding where this pointer error exists though. I have placed breakpoints through every step of the convert constructor and subsequent function calls within however my program doesn't throw the exception until it returns to main, seemingly after my program has executed completely.
#include "A4String.h"
A4String::A4String() {
data = new char[5];
data[0] = '\0';
capacity = 5;
}
A4String::~A4String() {
if (capacity != 0)
delete[] data;
}
//Copy Constructor
A4String::A4String(const A4String &right) {
cout << "copy" << endl;
data = new char[right.capacity + 1];
strcpy(data, right.data, capacity);
capacity = right.capacity;
}
//Convert Constructor
A4String::A4String(const char *sptr) {
cout << "convert" << endl;
capacity = (strlen(sptr)) + 1;
data = new char[capacity + 1];
strcpy(sptr, data, capacity);
}
//Assignment
A4String& A4String::operator = (const A4String & right) {
//if (capacity != 0) delete[] data;
data = new char[right.capacity + 1];
strcpy(data, right.data, capacity);
capacity = right.capacity;
return *this;
}
//Equivalence
bool A4String::operator == (const A4String &right) const {
return (strcmp(data, right.data)) == 0;
}
int A4String::length() const {
return capacity;
}
void A4String::addChar(char) {
//Not implemented yet
}
string A4String::toString() {
string str = "";
int i = 0;
while (data[i] != '\0') {
str += data[i];
i++;
}
return str;
}
void A4String::strcpy(const char *source, char* destination, int size)
{
for (int i = 0; i < 20; i++)
destination[i] = '\0';
int index = 0;
while (source[index] != '\0')
{
destination[index] = source[index];
index++;
}
destination[index] = '\0';
}
int A4String::strcmp(char *str1, char *str2)
{
if (*str1 < *str2)
return -1;
if (*str1 > *str2)
return 1;
if (*str1 == '\0')
return 0;
return strcmp(str1 + 1, str2 + 1);
return 0;
}
int A4String::strlen( char *s)
{
char *start;
start = s;
while (*s != 0)
{
++s;
}
return s - start;
}
The problem is your A4String::strcpy, the line
for (int i = 0; i < 20; i++)
destination[i] = '\0';
The destination has less than 20 characters, so it crashes.
Use of the hard code number 20 in the A4String::strcpy is not right. I suggest changing it to size.
void A4String::strcpy(const char *source, char* destination, int size)
{
// for (int i = 0; i < 20; i++)
for (int i = 0; i < size; i++)
destination[i] = '\0';
int index = 0;
// Add an additional check here also.
// while (source[index] != '\0' )
while (source[index] != '\0' && index < size)
{
destination[index] = source[index];
index++;
}
destination[index] = '\0';
}
Disclaimer Fixing the above function may not fix your crashing problem even though the use of 20 is most likely crashing your program. In other words, there might be other problems in your code too.