Reputation: 41
For the most part everything is working and it's able to build error free. However when I try to run it, it seems to crash. To be more specific, whenever I start my code and press 'a' or 'b', the program keeps crashing. Can someone tell me how to fix that?
#include <stdio.h>
#include <string.h>
int top=-1;
int word;
char stack_string[100];
void push(char word);
char pop(void);
int main()
{
char input;
char str[100];
int i;
printf("press [a] for palindrome check, [b] for string reversal:");
scanf("%s", input);
if (input == 'b'){
printf("Input a string: ");
scanf("%[^\n]s", str);
for(i=0;i<strlen(str);i++)
push(str[i]);
for(i=0;i<strlen(str);i++)
str[i]=pop();
printf("Reversed String is: %s\n",str);
}
else if(input == 'a'){
char str[100];
int count = 0;
printf("Input a string: ");
scanf("%[^\n]s", str);
for (i = 0; i < strlen(str); i++)
{
push(str[i]);
}
for (i = 0; i < strlen(str); i++)
{
if (str[i]==pop())
count++;
}
if (count == strlen(str))
printf("%s is a palindrome\n", str);
else
printf("%s is not a palindrome\n", str);
}
return 0;
}
void push(char word)
{
top=top+1;
stack_string[top]=word;
}
char pop()
{
word = stack_string[top];
top=top-1;
return word;
}
Upvotes: 4
Views: 6967
Reputation: 79
main problem is you are reading a string but comparing it to a single char
that's why if condition is not working
just convert
scanf( "%s", input);
to
scanf( "%c", &input);
that will be enough
Upvotes: 3
Reputation: 2899
the main problem is input stream
for single char input in scanf
we use scanf( "%c", &input);
but for whole non-space array of characters / string we use
scanf( " %s", str);
for string contains whitespace except new line
gets_s( str, sizeof( str ) ) ;
for your case
correct the following code
scanf( "%s", input);
to
scanf( "%c", &input);
Happy Coding
Upvotes: 6
Reputation: 48307
The problem is: you are getting the input with scanf("%s", input);
therefore the condition input == 'a'
is the same as "a" == 'a' which never meets
you need to get the input as a char using
scanf("%c", &input);
not
scanf("%s", input);
Upvotes: 2