2015-04-03 28 views
-1

我有象下面這樣的C代碼:如何在C中獲取未知長度的char *?

char* text; 
get(text); //or 
scanf("%s",text); 

但我嘗試運行此它打破。因爲我沒有給出text的尺寸。
爲什麼我沒有給出text的尺寸,因爲我不知道用戶打算輸入的文字大小是多少。 那麼,在這種情況下我該怎麼辦? 如果我不知道字符串的長度,我該如何閱讀文本?

+0

使用[getline](http://manpages.ubuntu.com/manpages/utopic/en/man3/getline.3.html) – BLUEPIXY 2015-04-03 21:12:04

回答

6

你可以試試這個

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

int main(void) 
{ 
    char *s = malloc(1); 
    printf("Enter a string: \t"); // It can be of any length 
    int c; 
    int i = 0; 
    /* Read characters until found an EOF or newline character. */ 
    while((c = getchar()) != '\n' && c != EOF) 
    { 
     s[i++] = c; 
     s = realloc(s, i+1); // Add space for another character to be read. 
    } 
    s[i] = '\0'; // Null terminate the string 
    printf("Entered string: \t%s\n", s); 
    free(s); 
    return 0; 
} 

注:切勿使用gets函數讀取一個字符串。它不再存在於標準C中。