簡體   English   中英

C 從控制台讀取多個帶有空格的單詞/參數

[英]C read multiple words/arguments with space from console

嗨,我是 C 新手,我希望用戶輸入類似inspect 2以顯示該示例中位置 2 處的數組值。

我無法讓它工作

    char input[20];
    scanf("%s", input);

    if (strcmp(strtok(input, " "), "inspect") == 0) {
     char str[20];
     int idx;
     printf("input was %s", input);
     idx = sscanf(input, "%s %d", str, &idx);
   }

它總是打印input was inspect但未讀取以下空格和數字? 檢查用戶是否輸入了“inspect”並獲取他之后輸入的索引的正確方法是什么?

謝謝你

你的選擇很少,你想選擇一個而不是把它們混在一起。

要讀取輸入,請考慮使用 fgets。 更安全,處理的例外更少。 我已經列出了等效的 sscanf,但它更難使用。 他們都將引入完整的“輸入”行。 請注意, fgets 還將包括尾隨的新行。

   // make buffer large enough.
char input[255] ;

if ( fgets(input, sizeof(input), stdin) != NULL ) {
   ...
}

// OR
if ( sscanf("%19[^\n]", input) = 1 ) {
} ;

對於解析:解析輸入字符串的選項很少。

在選項之間,我會投票支持 sscanf,因為它提供了對錯誤輸入、溢出等的最大驗證和保護。當 strtok 返回 NULL 時,strcmp(strtok(...)) 很容易導致 SEGV 錯誤。

使用 sscanf

  if ( sscanf(input, "inspect %d", &idx) ==1 ) {
     ... Show Element idx
  } ;

使用 strtok/strcmp

  if ( strcmp(strtok(input, " "), "inspect") == 0 ) {
      if ( sscanf("%d", strtok(NULL, " "), &idx) == 1 ) {
          .. Show element idx
      } ;
  } ;

使用 strtol

  if ( strcmp(strtok(input, " "), "inspect") == 0 ) {
      char *stptr = strtok(input, " "), *endptr = NULL ;
      idx = strtol(stptr, &endptr, 10) ;
      if ( endptr != stptr ) {
          .. Show element idx
      } ;
  } ;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM