2015-07-04 28 views
0

如何存儲使用空格輸入的字符串。 對於例如:字符串輸入使用換行可使用用於環路被存儲,然後被存儲到陣列中,同樣如何存儲其輸入爲一個單一的線串,但隨着空間存儲使用空格輸入的字符串

+3

可以使用的功能fgets和strtok的。 –

+0

'scanf(「%s」,str)'在循環中? –

+0

輸入後,我想將每個單詞存儲到數組中。 –

回答

1

使用fscanf%s格式指令。它有一個字段寬度,如果你有興趣避免緩衝區溢出(你應該是),例如char foo[128]; int x = fscanf(stdin, "%127s", foo); ...不要忘記檢查x

在閱讀這樣一個固定寬度的字段後,需要進行一些錯誤檢查。如果fscanf顯示最大字符數,則需要停止閱讀......流很可能會留下一些非空格字符,應該使用類似以下內容丟棄這些字符:fscanf(stdin, "%*[^ \n]");。您可能還想讓用戶知道他們的輸入已被截斷。

另外,如果你想閱讀一個未知長度的真正大的話你可以使用此功能,我寫道:

#include <ctype.h> 
#include <stdio.h> 
#include <stdlib.h> 

char *get_dynamic_word(FILE *f) { 
    size_t bytes_read = 0; 
    char *bytes = NULL; 
    int c; 
    do { 
     c = fgetc(f); 
    } while (c >= 0 && isspace(c)); 
    do { 
     if ((bytes_read & (bytes_read + 1)) == 0) { 
      void *temp = realloc(bytes, bytes_read * 2 + 1); 
      if (temp == NULL) { 
       free(bytes); 
       return NULL; 
      } 
      bytes = temp; 
     } 

     bytes[bytes_read] = c >= 0 && !isspace(c) 
          ? c 
          : '\0'; 
     c = fgetc(f); 
    } while (bytes[bytes_read++]); 
    if (c >= 0) { 
     ungetc(c, f); 
    } 
    return bytes; 
} 

實例:char *foo = get_dynamic_word(stdin);不要忘了free(foo); ...

將單詞分配給數組的例子?無problemo:

不要忘記free(bar[0]); free(bar[1]); /* ... */

+0

我正在嘗試從控制檯讀取輸出。不是來自文件。 –

+1

@TomJMuthirenthi:所以只需傳入'stdin'。 – alk

+1

'stdin'(*「console」*)是一個'FILE *',@TomJMuthirenthi – Sebivor

相關問題