2011-03-21 120 views
4

如果我想從命令行讀取任意長度的字符串,那麼最好的方法是什麼?從控制檯讀取未知長度的字符串

目前,我這樣做:

char name_buffer [ 80 ]; 
int chars_read = 0; 
while ((chars_read < 80) && (!feof(stdin))) { 
    name_buffer [ chars_read ] = fgetc (stdin); 
    chars_read++; 
} 

但我能做些什麼,如果字符串的長度超過80個字符?顯然,我可以只是初始化數組到更大的數字,但我確定必須有一個更好的方法來給數組使用malloc或更多的空間?

任何提示都會很棒。

+0

可能重複http://stackoverflow.com/questions/3598351/reading-字符串與undefined-length-in-c) – 2011-03-21 09:13:34

回答

13

發現不久前在網上這個地方,它真的有用:

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

int main() 
{ 
    unsigned int len_max = 128; 
    unsigned int current_size = 0; 

    char *pStr = malloc(len_max); 
    current_size = len_max; 

    printf("\nEnter a very very very long String value:"); 

    if(pStr != NULL) 
    { 
    int c = EOF; 
    unsigned int i =0; 
     //accept user input until hit enter or end of file 
    while ((c = getchar()) != '\n' && c != EOF) 
    { 
     pStr[i++]=(char)c; 

     //if i reached maximize size then realloc size 
     if(i == current_size) 
     { 
         current_size = i+len_max; 
      pStr = realloc(pStr, current_size); 
     } 
    } 

    pStr[i] = '\0'; 

     printf("\nLong String value:%s \n\n",pStr); 
     //free it 
    free(pStr); 
    pStr = NULL; 


    } 
    return 0; 
} 
([在C未定義長度字符串閱讀]的
+0

謝謝,這真棒!爲什麼c在開始時設置爲EOF?爲什麼它是一個int而不是char? – Sam 2011-03-21 10:10:26

+0

它被設置爲EOF以初始標記輸入字符串的最後一個點,並且它位於INT中,因爲輸入是首先以ASCII值輸入的。 – 2011-03-21 10:18:07

+0

如果您發現有用的答案,請將其標記爲正確並給出upvote。提前致謝。 – 2011-03-21 10:18:45

2

使用realloc()分配緩衝區,並在緩衝區滿時進行擴展。