我正在尝试将一个char附加到预先存在的动态char数组上,然后打印出新数组。正如标题所示,我想避免使用字符串库和容器。
我看到了similar question并试图为我的目的修改代码,但我的问题仍未解决。我的问题是它在main中工作,但是当我尝试将它抽象为一个方法时,它似乎不再像现有的那样将旧数组复制到一个新的更大的数组中。它一直工作直到用户说他们想要增加数组的大小,但是在调用方法后的某个地方,它没有按预期执行,因为没有打印附加char输入的提示。 / p>
非常感谢帮助;这是我到目前为止的代码:
在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.";
}
放入课程方法时不起作用:
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;
}
答案 0 :(得分:0)
你把很多东西都搬进了你的班级,现在main中的代码引用了与推回功能不同的东西。
您应该从主
中删除所有这些内容char* userArray = NULL;
int n;
char input;
char response;
而是在main中引用example.userArray,example.n等。