Plasmeious Plasmeious - 17 days ago 6
C Question

c: strcmp Not Stopping At Conditional Statement It Should Hit

I'm learning to create multi-file programs for one of my classes. Ultimately I need to implement a stack and do some stuff with the stack. Before I began implementing the stack I wanted to make sure my files were all linked together properly with a header file. For some reason when the user inputs "pop" or "print" the conditional statement is not triggered and the method in stack.c is not called. I've been looking at this for awhile and haven't gotten anywhere. Thank you for the help

MAIN.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "stack.h"
void pop(char list[]);
void print(char list[]);
void push(char list[]);
int main(void)
{
char input[5];
char test[5];
while( strcmp("exit",input) != 0)
{
printf("Please enter a command. \n");
fgets(input,sizeof(input),stdin);
if(strcmp("pop",input)==0)
{
pop(test);
}
else if(strcmp("push",input)==0)
{
push(test);
}
else if (strcmp("print", input)==0)
{
print(test);
}
}
return 0;
}


STACK.c

#include <stdio.h>
#include <stdlib.h>
#include "stack.h"

void pop(char list [])
{
printf("This is in the stack file in pop\n");
}
void push(char list [])
{
printf("This is in the stack file in push\n");
}
void print(char list[])
{
printf("This is in the stack file in print\n");
}


Console Output

Please enter a command.
push
This is in the stack file in push
Please enter a command.
Please enter a command.
pop
Please enter a command.
print
Please enter a command.
Please enter a command.
exit

Answer

Three things:

  1. The line read by fgets() will include \n at the end. Test for strcmp("word\n", input)==0.
  2. 5 is not sufficient size for input since you need to be testing for newlines ("push\n\0" is 6 bytes; "print\n\0" is 7 bytes)
  3. You test for strcmp("exit", input) without input being initialized. This is undefined behavior. Set input to be all-zeroes before beginning your loop.