为什么我的代码在检查 'exit' 字符串时没有在循环中终止?
Why isn't my code terminating within a loop when checking for 'exit' string?
我的程序应该在用户键入 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;
}
很抱歉,我没有足够的声誉点数来添加评论,但@lundman 是正确的。我认为您不需要创建指向条目的指针。此外,您正在以相反的顺序检查 "exit"。我尝试并编辑了代码;这似乎有效:
#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;
}
我的程序应该在用户键入 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;
}
很抱歉,我没有足够的声誉点数来添加评论,但@lundman 是正确的。我认为您不需要创建指向条目的指针。此外,您正在以相反的顺序检查 "exit"。我尝试并编辑了代码;这似乎有效:
#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;
}