[英]reading command line argument
誰能指點我這邊的問題? 這會編譯,但不會打印任何內容。 我需要將命令行參數中的字符串與字符串“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;
}
我的ESP建議您在交互式編輯器/調試器(如Microsoft Studio)中運行它。 您可能尚未將環境配置為傳遞任何命令行參數,因此您不希望看到nothing
輸出。
但是,您訪問不存在的argv[1]
,創建seg-fault,程序在有任何輸出之前中止。
要解決此問題,請首先檢查argc
的值,並確保不訪問無效內存。
另外,我建議在每個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;
}
當你運行它時,你應該看到:
$prompt: myprogram
No arguments passed!
$prompt: myprogram hello
Yes, I find it
$prompt: myprogram world
nothing
問題是您用來運行它的命令。 正如你評論的那樣:
我運行程序>測試你好或>測試嗨,輸出什么都沒有
>
是重定向輸出,最終不會給你命令行參數。 你想要的只是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;
}
和輸出
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.