我正在学习为我的一个课程创建多文件程序。最终,我需要实现一个堆栈并对堆栈做一些事情。在我开始实现堆栈之前,我想确保我的文件都与头文件正确链接在一起。出于某种原因,当用户输入“pop”或“print”时,不会触发条件语句,并且不会调用stack.c中的方法。我一直在看这个并没有得到任何结果。谢谢你的帮助
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");
}
控制台输出
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
答案 0 :(得分:1)
我建议使用strstr()而不是strcmp()。如果使用strstr(),则无需在要搜索的字符串中提及'\ n'。
strstr()函数在字符串haystack中查找第一次出现的子串针。 为了更好地理解你可以访问, http://man7.org/linux/man-pages/man3/strstr.3.html
代码看起来像,
while( strstr(input,"exit") == NULL)
{
printf("Please enter a command. \n");
memset(input,0,sizeof(input));
fgets(input,sizeof(input),stdin);
if(strstr(input,"pop"))
{
printf("pop\n");
}
else if(strstr(input,"push"))
{
printf("push\n");
}
else if (strstr(input,"print"))
{
printf("print\n");
}
}
我同意@Govind Parmar的说法,5个字节不足以用于输入缓冲区。您需要声明7字节的输入缓冲区。
答案 1 :(得分:0)
三件事:
fgets()
读取的行最后会包含\n
。测试strcmp("word\n", input)==0
。input
来说不够大,因为您需要测试换行符("push\n\0"
是6个字节; "print\n\0"
是7个字节)strcmp("exit", input)
初始化的情况下测试input
。这是未定义的行为。在开始循环之前将input
设置为全零。