【发布时间】:2019-09-27 15:32:41
【问题描述】:
我们的老师给我们布置了作业,使用数据结构“Stack”检查单词的回文。
以下是我为以下问题编写的代码:-
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include <stdbool.h>
struct Stack
{
int top;
int capacity;
char *array;
};
void push(struct Stack stack, char a) //Push function.
{
stack.array[++stack.top] = a; //Helps to push charater to a stack.
}
char pop(struct Stack stack) //Pop function.
{
return stack.array[stack.top--]; //Helps to pop character from a stack.
}
int main(void)
{
struct Stack original; //Original stack where the "Original" word will be pushed.
original.top = -1;
original.capacity = 10;
original.array = calloc(original.capacity, sizeof(char));
struct Stack checker; //Another stack that "Checks" whether the word is palindrome or not.
checker.top = -1;
checker.capacity = 10;
checker.array = calloc(checker.capacity, sizeof(char));
while(getchar()!='\0') //Getting all the characters from the stdin buffer and pushing it into "Original" stack.
{
push(original, getchar());
}
while(original.top != -1)
{
push(checker,pop(original)); //Popping from "Original" stack and pushing it to "Checker" stack.
}
while(checker.top != -1)
{
original.top = checker.top;
if(original.array[original.top] != checker.array[checker.top]) //Checking every character in the stack if it is excatly same or not.
{
printf("It is not a palindrome.\n");
return EXIT_SUCCESS;
}
else
{
checker.top = checker.top - 1;
}
}
if(checker.top == -1)
{
printf("It is a palindrome.\n");
}
return 0;
}
无论我在以下行中遇到问题:-
while(getchar()!='\0') //Getting all the characters from the stdin buffer and pushing it into "Original" stack.
{
push(original, getchar());
}
以下循环无限运行。我添加以下行的目的是我想将stdin buffer 和push 中的单个字符添加到original 堆栈中,直到遇到'\0'。
我在这里做错了什么?这样做违法吗?
附录:-
示例输入 1:- 公民
预期输出:- 这是一个回文。
示例输入 2:- 夫人
预期输出:- 这不是回文。
附言
以下代码:-
while(getchar()!='\0') //Getting all the characters from the stdin buffer and pushing it into "Original" stack.
{
push(original, getchar());
}
现在已替换为:-
int c;
int i = 0;
while ( i < original.capacity && ( c = getchar() ) != EOF && c != '\n' )
{
push(original, c );
++i;
}
现在工作完美,但是现在,对于每个单词,我的代码都会给出输出:-
这是一个回文。
我在哪里错误地应用了堆栈的概念?
【问题讨论】:
-
getchar()不太可能从文本文件中读取'\0'。不仅如此,您还可以扔掉读取的字符并推动下一个字符。 -
@WeatherVane
getchar()无法从stdin读取'\0'? -
是的,它可以 - 如果有,但在文本文件中没有。行以换行符结束。
-
int c; while((c = getchar()) != '\n' && c != EOF) { push(original, c); } -
@SwarnimKhosla 不。阅读该函数的文档。
标签: c while-loop stack palindrome getchar