【发布时间】:2015-09-09 12:39:12
【问题描述】:
有时我在编程方面会遇到一些麻烦,但我一般都很好,并且总是有完美理解这个概念的问题,但是当我尝试实现一个实际的程序来执行操作时,我碰壁了。
我有一个任务要处理,我必须接受一个输入字符串,将其逐个字符地读入堆栈(使用链表),然后将结果从堆栈中弹出,将其存储到一个新字符串中然后比较字符串以确定该特定输入字符串是否为回文。
到目前为止,我似乎遇到的唯一问题是(希望)在程序的最后。当我尝试从堆栈中弹出每个字符并将它们单独存储在一个字符串中时,我遇到了一个问题,Visual Studio 告诉我:“error C2664: 'Stack::pop' : cannot convert parameter 1 from 'unsigned int ' to 'char &'"
void Stack::pop(char &input_string) {
StackNode* temp;
if (isEmpty()) {
cout << "The stack is empty." << endl;
}
else {
input_string = top->value;
temp = top->next;
delete top;
top = temp;
}
}
int main () {
Stack stringStack;
string input_string;
string reverse_input;
cout << "Input the desired string to determine if it is a palindrome or not. No spaces please." << endl;
cin >> input_string;
for (unsigned int i=0; i < input_string.length(); i++) {
stringStack.push(input_string[i]);
}
while (!stringStack.isEmpty()) {
for (unsigned int j=0; j < input_string.length(); j++) {
stringStack.pop(j) = reverse_input[j];
}
}
if (reverse_input == input_string) {
cout << "Your input is a palindrome!" << endl;
}
else {
cout << "Your input was not a palindrome, try again!" << endl;
}
system ("PAUSE");
}
我意识到它告诉我不能将 j 传递给 pop 函数来弹出值,因为我声明的 pop 函数需要一个 char 值。
是否可以通过将 pop 函数的输入更改为整数,然后使用 pop 函数返回 char 值来解决此问题?
我排除了cpp文件中除了pop函数和主执行函数之外的所有其他函数,如果你出于某种原因需要查看其他部分,请告诉我。
提前感谢您的帮助。非常感谢。
【问题讨论】:
-
while(!stringStack.esEmpty())有必要吗?如我所见,您只需迭代for一次即可填充reverse_input列表,假设for工作正常,实际上,您只能使用while而不是for -
这
char &input_string具有误导性,因为您声明的是对单个字符的引用而不是字符串。对 1 个或更多个字符使用std::string。 -
您没有停下来阅读错误消息并查看生成它的代码。您正在传递循环索引
j,其中需要一个字符。如果您查看产生错误的行,答案就在那里。