I'm trying to append a single char onto a pre-existing dynamic char array, and then print out the new array. As the title suggests, I want to avoid using the string library and containers.
I saw a similar question and have tried to modify the code for my purposes, but my problem remains unsolved. My issue is that it works in main, but when I try to abstract it into a method, it no longer seems to copy the old array into a new, larger one as intended. It works up until the point where the user says they would like to increase the size of the array, but then somewhere after calling the method, it doesn't perform as expected since the prompt for the additional char input doesn't print.
Help would be greatly appreciated; here's the code I have so far:
Works in main:
std::cout << "Would you like to append another character to the end of your string? Y/N ";
std::cin >> response;
if(response=='Y') {
delete[] userArray;
char* largerArray = new char[n+1];
std::copy(userArray, userArray + std::min(n, n+1), largerArray);
userArray = largerArray;
std::cout << "Input char to append: ";
std::cin >> input;
largerArray[n] = input;
for (int j = 0; j < n+1; ++j) {
std::cout << "x[" << j << "] = " << largerArray[j] << std::endl;
}
} else {
std::cout << "Nothing new added.";
}
Does not work when put into class method:
class MyClass{
public:
char* userArray;
int n;
char input;
char response;
public:
void pushBack();
MyClass();
};
MyClass::MyClass(){}
void MyClass::pushBack()
{
delete[] userArray;
char* largerArray = new char[n+1];
std::copy(userArray, userArray + std::min(n, n+1), largerArray);
userArray = largerArray;
std::cout << "Input char to append: ";
std::cin >> input;
largerArray[n] = input;
for (int j = 0; j < n+1; ++j) {
std::cout << "x[" << j << "] = " << largerArray[j] << std::endl;
}
}
int main()
{
MyClass example;
char* userArray = NULL;
int n;
char input;
char response;
std::cout << "How many chars would you like to concatenate into a string? ";
std::cin >> n;
userArray = new char[n];
std::cout << "Enter the " << n << " characters: ";
for (int i=0;i<n;i++) {
std::cin >> input;
userArray[i] = input;
}
std::cout << "Would you like to append another character to the end of your string? Y/N ";
std::cin >> response;
if(response=='Y') {
example.pushBack();
} else {
std::cout << "Nothing new added.";
}
return 0;
}
delete[]?delete[] userArray; std::copy(userArray, ...;