我需要幫助的顯示名稱類似這樣的命令行(我不知道該怎麼解釋)命令行用C參數Ç
$:Enter your name: Test
$:Test>
但是當你繼續按回車它仍然顯示測試>
$:Test>
$:Test>
那麼,我們如何得到的argv [0],做這樣的事情(對不起,我不能大概解釋)
謝謝
我需要幫助的顯示名稱類似這樣的命令行(我不知道該怎麼解釋)命令行用C參數Ç
$:Enter your name: Test
$:Test>
但是當你繼續按回車它仍然顯示測試>
$:Test>
$:Test>
那麼,我們如何得到的argv [0],做這樣的事情(對不起,我不能大概解釋)
謝謝
如果你腦子裏想的,而殼狀的程序,也許使用以下couldbe:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#define BUFSIZE 64
int main() {
char prompt[BUFSIZE];
char command[BUFSIZE];
char *prefix = "$:";
char *suffix = ">";
printf("%s%s%s", prefix, "Enter your name:", suffix);
fgets(prompt, BUFSIZE, stdin);
prompt[strlen(prompt)-1] = '\0'; // get rid of the \n
while (true) {
printf("%s%s%s", prefix, prompt, suffix);
fgets(command, BUFSIZE, stdin);
if (strncmp(command,"Quit",4) == 0)
break;
}
return 0;
}
非常感謝你這是我尋找的 –
命令行參數存儲在char ** argv中,並且它們是argc。
int main(int argc, char **argv)
{
int i=0;
for(i=0; i< argc; i++)
printf("argument number %d = %s\n", i, argv[i]);
return 0;
}
的argv [0]是程序的名稱被執行,所以的argc總是至少== 1(或更多)
只要有可能,應使用getopt的(),以便順序你的參數無關緊要。例如,假設您想要獲取大小的整數參數,執行模式的整數,並指定是否以「安靜模式」運行。進一步假設「-h」應該打印幫助並退出。這樣的代碼將會訣竅。 「s:m:hq」字符串表示「-s」和「-m」提供參數,但其他標誌不提供參數。
int main() {
// parse the command-line options
int opt;
int size = DEFAULT_SIZE, mode = DEFAULT_MODE, quiet = 0;
while ((opt = getopt(argc, argv, "s:m:hq")) != -1) {
switch (opt) {
case 's': size = atoi(optarg); break;
case 'm': mode = atoi(optarg); break;
case 'q': quiet = 1; break;
case 'h': usage(); return 0;
}
}
// rest of code goes here
}
當然,如果optarg爲空,則應該添加錯誤檢查。另外,如果你使用C++,「string(optarg)」是你的case語句設置一個std :: string來保存一個在argv中存儲爲char *的值的適當方法。
我認爲這個問題是解析用戶輸入的一個類似shell的交互式程序 – jev
我回答了有關如何獲得命令行參數這裏之前的問題:http://stackoverflow.com/問題/ 18937861/C-如何做通吃多檔換參數/ 18939140#18939140。看看是否有助於你開始。 – lurker
你想寫一個交互式程序嗎?還有一種設置該程序提示的方法? –
還是你想重命名命令行提示符? – Duck