gpt4 book ai didi

c - While 循环受strcmp if 语句影响。为什么是这样?

转载 作者:行者123 更新时间:2023-11-30 14:57:09 25 4
gpt4 key购买 nike

基本上,我在程序的一部分中遇到了下面的 while 循环问题。

这是我遇到问题的代码部分:

            char *nameOfTheCommand;
char *arrayArgs[500];
//track for redirection. If set, gives position of the file name. Else it equals zero
int redirectionCheck=0;
arrayArgs[0]=token;
int i;
i=0;
//While still arguments to take in, do this
while(arrayArgs[i]!=NULL)
{
i++;
arrayArgs[i]=strtok(NULL, " \n");
if(strcmp(arrayArgs[i], "<")==0)
{
redirectionCheck=i;
}
}

我想要代码做的就是循环 strtok 并将其设置为等于 arrayArgs[i]。如果 strtok 碰巧拉出了“<”符号,那么我希望将重定向设置为 i。

这看起来很简单。然而,如果我在 while 循环中包含 if 语句,则似乎 while 循环退出并且之后没有代码执行。我在 while 循环之后放置了一个 printf 语句,它不会打印任何内容,这就是我知道它就像 while 循环只是立即停止其后运行的所有其他内容的原因。

但是,如果我不包含 if 语句,我的代码就可以正常运行。

有人可以向我解释一下为什么这个 if 语句似乎导致我的 while 循环无法正常运行吗?就像这样,如果我包含它,那么 while 循环似乎不会执行它后面的东西。感谢您提供任何信息。

最佳答案

在循环的最后一次迭代中,将 NULL 传递给 strcmp。这可以通过重新安排循环来避免:

i = 1;
// read subsequent tokens
while((arrayArgs[i] = strtok(NULL, " \n")) != NULL)
{
if(strcmp(arrayArgs[i], "<") == 0)
{
redirectionCheck = i;
}
i++;
}

但我还会添加对 i 值的检查。

关于c - While 循环受strcmp if 语句影响。为什么是这样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44102407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com