有人能指出我这边的问题吗?这会编译,但不会打印任何内容。我需要将命令行参数中的字符串与字符串“hello”进行比较。 谢谢!
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
if (argc == 0)
{
printf("No arguments passed!\n");
}
char *str = argv[1];
if(strcmp("hello", str)==0)
{
printf("Yes, I find it");
}
else
{
printf("nothing");
}
return 0;
}
答案 0 :(得分:2)
我的ESP建议您在交互式编辑器/调试器(例如Microsoft Studio)中运行它。您可能尚未将环境配置为传递任何命令行参数,因此您希望将nothing
视为输出。
但是,您访问不存在的argv[1]
,创建了一个seg-fault,程序在有任何输出之前就会中止。
要解决此问题,请先检查argc
的值,并确保您没有访问无效内存。
另外,我建议在每个\n
的末尾添加一个printf
,以帮助将任何缓冲的输出刷新到控制台。
int main(int argc, char *argv[])
{
if (argc == 0)
{
printf("No arguments passed!\n");
}
else if(strcmp("hello", argv[1])==0)
{
printf("Yes, I find it\n");
}
else
{
printf("nothing\n");
}
return 0;
}
当你运行它时,你应该看到:
$prompt: myprogram
No arguments passed!
$prompt: myprogram hello
Yes, I find it
$prompt: myprogram world
nothing
答案 1 :(得分:0)
问题是您用来运行它的命令。正如你评论的那样:
我运行程序&gt;测试你好或者>测试嗨,输出什么都没有
>
重定向输出,最终没有给出命令行参数。你想要的只是program hello
没有输出重定向。
答案 2 :(得分:0)
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
if (argc < 2 || 0 != strcmp("hello", argv[1]))
printf("nothing\n");
else
printf("yes, found it\n");
return 0;
}
和输出
bash-3.2$ gcc 1.c -o 1
bash-3.2$ ./1 hello1
nothing
bash-3.2$ ./1 hello
yes, found it
bash-3.2$ ./1
nothing
答案 3 :(得分:0)
尝试将您的程序称为“test”