【问题标题】:Why isn't my code terminating within a loop when checking for 'exit' string?为什么在检查“退出”字符串时我的代码没有在循环内终止?
【发布时间】: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


【解决方案1】:

很抱歉,我没有足够的声望点来添加评论,但@lundman 是正确的。我认为您不需要创建指向条目的指针。此外,您正在以相反的顺序检查“退出”。我尝试并编辑了代码;这似乎有效:

 #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]=='e' &&  entry[1]=='x' && entry[2]=='i' && entry[3]=='t')
        {

            printf("Inside of exit");//printf("Exiting");
            exit(0); //exit(system call)
        }
        printf("msh> you typed %s %c %c %c %c\n",entry,entry[3],entry[2],entry[1],entry[0]); //returning user input
    }
    return 0;
}

【讨论】:

  • 你可以使用string.h然后简化doif(strstr(entry, "exit"))来查看exit是否包含在入口字符串中,如果你需要exit这个词在开始然后检查strstr的结果指向与 entry 相同的位置。只是看起来更干净一些。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-28
  • 2016-04-27
  • 1970-01-01
  • 1970-01-01
  • 2021-09-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多