I'm trying to use my own String class to create a text based adventure game in the console. Although I'm having trouble with a pointer losing it's value. Here are cut down versions of the classes I think are causing the problem. ReadAndLog() sets the value of 'string' to the users input. When ToUpper() is called the value is still correct, however upon entering the length function the value at the location of 'string' is garbage data. Any insight into what is happening would be great. Thanks in advance.
String.h:
#ifndef STRING_H_
#define STRING_H_
class String
{
public:
String();
~String();
int Length();
String & ToLower();
String & ToUpper();
void ReadAndLog();
private:
char * string;
};
#endif
String.cpp:
#include "String.h"
String::String()
{
string = nullptr;
}
String::~String()
{
if (string != nullptr)
{
delete[] string;
string = nullptr;
}
}
int String::Length()
{
if (string == nullptr)
return 0;
else
{
for (int i = 0; true; i++)
{
if (string[i] == '\0')
{
return i;
}
}
}
}
String & String::ToLower()
{
int length = Length();
for (int i = 0; i < length; i++)
{
if (string[i] >= 'A' && string[i] <= 'Z')
string[i] += 32;
}
return *this;
}
String & String::ToUpper()
{
int length = Length();
for (int i = 0; i < length; i++)
{
if (string[i] >= 'a' && string[i] <= 'z')
string[i] -= 32;
}
return *this;
}
Edit - ReadAndLog Changed
void String::ReadAndLog()
{
char charArray[256];
std::cin.getline(charArray, 256);
for (int i = 0; true; i++)
{
if (charArray[i] == '\0')
{
if (string != nullptr)
{
delete[] string;
string = nullptr;
}
string = new char[i + 1];
for (int j = 0; j < i; j++)
{
string[j] = charArray[j];
}
string[i] = '\0';
break;
}
}
File::LogEntry((String)"User", string);
}
The code that is calling is in Game.cpp which calls:
String input;
input.ReadAndLog();
input.ToUpper();