[英]reading command line argument
can anyone point me to the problem over here? 谁能指点我这边的问题? This compiles but it won't print anything.
这会编译,但不会打印任何内容。 I need to compare the string from command line argument with the string "hello".
我需要将命令行参数中的字符串与字符串“hello”进行比较。 Thanks!
谢谢!
#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;
}
My ESP suggests that you're running this in an interactive editor/debugger, such as Microsoft Studio. 我的ESP建议您在交互式编辑器/调试器(如Microsoft Studio)中运行它。 You probably haven't configured the environment to pass any command-line parameters, so you expect to see
nothing
as your output. 您可能尚未将环境配置为传递任何命令行参数,因此您不希望看到
nothing
输出。
However, you access argv[1]
, which does not exist, creating a seg-fault, and the program aborts before there is any output. 但是,您访问不存在的
argv[1]
,创建seg-fault,程序在有任何输出之前中止。
To fix this, check the value of argc
first, and make sure you don't access invalid memory. 要解决此问题,请首先检查
argc
的值,并确保不访问无效内存。
Also, I recommend putting a \\n
at the end of each printf
to help flush any buffered output to the console. 另外,我建议在每个
printf
的末尾加一个\\n
来帮助将任何缓冲的输出刷新到控制台。
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;
}
When you run this, you should see: 当你运行它时,你应该看到:
$prompt: myprogram
No arguments passed!
$prompt: myprogram hello
Yes, I find it
$prompt: myprogram world
nothing
The problem is the command you're using to run it. 问题是您用来运行它的命令。 As you commented:
正如你评论的那样:
i run program > test hello or > test hi and the output is nothing
我运行程序>测试你好或>测试嗨,输出什么都没有
The >
is redirecting output, and ends up giving you no command line arguments. >
是重定向输出,最终不会给你命令行参数。 What you want is simply program hello
without the output redirection. 你想要的只是
program hello
而没有输出重定向。
#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;
}
and output 和输出
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
尝试将您的程序称为“测试”不同的东西
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.