C:未找到bash事件

时间:2018-11-20 13:17:37

标签: c bash events

你好,所以我没有任何可以帮助我的朋友,当我测试这段代码时,我会得到这个错误

./main "Hello World!" "ld"
-bash: !": event not found

这是怎么回事

这是主要的:

#include <stdio.h>
#include <err.h>
#include <string.h>
int main (int argc, char *argv[]) 
{

int p = 0;
int q = 1;
int place = 0;
int check = 0;
char position[10] = ""; // i think the error is here

while (argv[1][p] != '\0')
{
    if (argv[1][p] == argv[2][0])
    {
        place = p;
        while (argv[2][q] != '\0' && argv[1][p + q] != '\0' && argv[2][q] == argv[1][p + q])
            { 
            q += 1;
            }
        if (argv[2][q] == '\0')
        {
            check = 1;
            printf("%s\n", argv[1]); //i think the error is here
            for (int n = 0; n < place; n += 1) //i think the error is here
            {
                strcat(position, " "); //i think the error is here
            }
            strcat(position, "^"); //i think the error is here
            printf("%s\n", position); //i think the error is here

        }
    }
    p += 1;
}
if (check == 0)
{
    printf("Not found!\n");
}

return 0 ; // return 0
}

我添加了评论,以便您可以提供帮助

以及如何创建

char position[10] = "";

没有给出我尝试的长度

char position[] = "";

但无法编译

2 个答案:

答案 0 :(得分:3)

简短回答

带有感叹号,请使用单引号。

./main 'Hello World!' 'ld'

长答案

感叹号在Bash中做了一些有趣的事情。 Read more... unix.stackexchange

  

感叹号是bash历史扩展中的一部分。要使用它,您需要将其用单引号引起来。

甚至用echo尝试!“都会给出

$ echo "Hello World!"
-bash: !: event not found

可以使用双引号,但是您可能需要一个反斜杠。

  

请注意,在双引号中,感叹号之前的反斜杠会阻止历史扩展,但在这种情况下,不会删除反斜杠。

因此./main "Hello World\!" "ld"也可以使用,但是您可能需要考虑C / C ++中的反斜杠。

请注意,感叹号的行为可能已更改。执行echo "Hello World!"可以在某些bash版本上工作。 致谢本杰明W。

答案 1 :(得分:0)

我认为是“!”可能会导致您的bash外壳出现问题。我在我的电脑上运行它没有任何问题。如果您尝试我的代码但失败了,请尝试以以下方式运行

./ main“ Hello World” ld

代码中的逻辑令人困惑,因为您尝试直接使用argv [1]和argv [2]输入。虽然可以做到,但是编写方式却很难遵循。

我通过重命名变量降低了代码的复杂性,以便您可以更轻松地遵循逻辑。

我还添加了一个子例程来执行字符串比较。当然,有一个库strcmp()函数,由于某些要求,我不确定是否避免使用该函数。您可以修改它以使用std strcmp()。

好的代码应该用变量名记录下来。这是我想出的:

#include <stdio.h>
#include <string.h>

/* compare two c strings.  Return 0 if equivalent. Return -1 if not.
 * Assumes that the strings are terminated with a '\0' character */
int homegrown_strcmp(char* str1, char* str2) {

    while( *str2 != '\0') {
        if(*str1 != *str2)
            return -1;
        str1++;
        str2++;
    }
    return 0;

}

int main(int argc, char *argv[])
{


    char* haystack = argv[1]; /* This is the string we are searching inside */
    char* needle = argv[2]; /* This is what we are looking for */

    char* poker = haystack;  /* We will use this to poke into our haystack until
 * we find our needle or fail */

    unsigned int position = 0;
    while(*poker != '\0') {
        if(homegrown_strcmp(poker, needle) == 0) {
            printf("Found at position %u\n", position);
            return 0;
        }
        poker++;
        position++;
    }
    printf("Not found\n");
    return -1;
}