【发布时间】:2017-02-07 01:37:55
【问题描述】:
当用户键入 exit 时,我的程序应该退出,类似于它在 shell 中的完成方式。首先我在网上查看是否可以在循环中调用 syscall,但后来我注意到数组中字符的索引是错误的。为什么这些会发生变化;当我运行程序并输入 exit 时,我让程序射出第三个索引以进行测试,它返回“e”。所以我认为它可能已经被翻转并翻转了所有值,我的退出仍然不起作用。对潜在问题可能有什么想法?
#include <stdio.h>
//Abstract: This program runs a script to emulate shell behavior
#define MAX_BIN_SIZE 100
int main() { //Memory allocation
char * entry[MAX_BIN_SIZE];
while(1)
{
printf("msh>");
fgets(entry,MAX_BIN_SIZE,stdin); //Getting user input
if(entry[0]=='t' && entry[1]=='i' && entry[2]=='x' && entry[3]=='e')
{
//printf("Exiting");
exit(0); //exit(system call)
break;
printf("Inside of exit");
}
printf("msh> you typed %s %c %c %c %c",entry,entry[3],entry[2],entry[1],entry[0]); //returning user input
}
return 0;
}
【问题讨论】:
-
当您使用调试器查看时,条目包含什么?你测试它是否有'tixe',它可能不包含那个。 (以及 BLUEPIXY 所说的)
-
char * entry[MAX_BIN_SIZE];-->char entry[MAX_BIN_SIZE]; -
您应该已经收到了一些编译器警告,提示您这段代码的错误所在。阅读它们。它们很重要。
-
绝对不是倒退。也许你有一些领先的空间?您应该检查 fgets() 的返回,然后检查:
printf("|%s|\n", entry);看看。 -
char *entry[MAX_BIN_SIZE]将创建一个指针数组,fgets 将填充为字节,然后您尝试将其与“tixe”作为指针进行比较。
标签: c arrays system-calls c-strings procedural-programming