2016-04-18 91 views
-2

這裏是一個程序,它在本程序中打印一些關於我自己的信息 如果用戶掃描/ n其打印名稱和 等,但是當我使用gcc運行此程序時,在所有。 我需要使用argv和argc來掃描參數。 我該如何解決?使用argv和argc打印

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#define SIZE 10 

int main(int argc, char** argv) 
{ 
    for (int i = 1; i < SIZE; i++) 
    { 
     if (argv[i] == ' ') 
     { 
      break; 
     } 
     if (argv[i] == 'n' || argv[i] == 'b' || argv[i] == 'f' || argv[i] == '?' && argv[i - 1] == '/') 
     { 
      switch (i) 
      { 

      case 'n': 
       printf("my name is : Daniel Zingerman \n"); 
       break; 
      case 'b': 
       printf("my birth date is: 2/11 \n"); 
       break; 
      case 'f': 
       printf("my favorite food is: ice cream \n"); 
       break; 
      case '?': 
       printf("the instruction of the program:"); 
       printf("There is a lot of parameters you can scan into the program:"); 
       printf("1. /n - printing the name"); 
       printf("2. /b - printing the birth date"); 
       printf("3. /n - printing the favorite food"); 
       printf("4. /? - printing the instructions"); 

       break; 
      } 
     } 


    } 
    system("pause"); 
    return(0); 
} 
+0

什麼是你遇到了這個程序的第一個驚喜? – fluter

+0

使用string.h中的strcmp比較字符串。而ARGC應該限制你的循環,而不是SIZE。 – jboockmann

+0

'case'/ n'究竟是什麼:'? –

回答

0

您應該使用argc值來知道什麼是最後一個參數。或者你應該測試argv[i] == NULL。您好像不明白argvchar **,所以argv[i]char *,而不是char

還學會使用getopt()或getopt_long()。

0

argv[]陣列與節目名稱在argv[0]創建,然後用空格
分離的命令行參數/ N/B/F將在argv[1], argv[2] & argv[3]返回,而不是作爲在argv[1]

一個單一的「字串」

使用argc限制要測試的argv[]有多少元素,讓你不出門界:
for (int i = 1; i < argc; i++) {

現在,您需要檢查是否有有效的命令行參數:
if ((strcmp(argv[i], "/n") == 0) || ...

當你需要的情況下測試的整數值,使用的argv第二元素[I]:
switch (argv[i][1]) {