2014-04-29 62 views
-1

有一個完成的項目,這不是我的。它運作良好,但如果我建,我得到一個警告:我應該使用什麼,而不是獲取?

the 'gets' function is dangerous and should not be used.

我必須現在解決這個項目,但我不知道,如何更換此功能

+2

嘗試[搜索計算器(http://stackoverflow.com/questions/3302255/c -scanf-vs-gets-vs-fgets)或[互聯網](https://www.google.com/search?q=what+to+use+instead+of+gets&oq=what+to+use+instead +的+得到&AQS = chrome..69i57j0l2.5279j0j7&的SourceID =鉻&es_sm = 93&即= UTF-8)。 – crashmstr

回答

2

使用fgets()stdin流。

請注意,與gets()不同,fgets()不會在輸入結尾刪除換行符,前提是它適合緩衝區。

如果剝離換行,當輸入超過你可能會寫一個包裝,如所提供的緩衝處理行爲:

char* read_line(char* buffer, size_t buffer_len) 
{ 
    char* line = fgets(buffer, buffer_len, stdin) ; 
    char* nl = strchr(buffer, '\n') ; 
    if(nl != 0) 
    { 
     // Replace newline character with nul 
     *nl = 0 ; 
    } 
    else 
    { 
     // If buffer was shorter than the line - read and discard rest of line. 
     while(getchar != '\n') { \* do nothing*\ } 
    } 

    return line ; 
} 
相關問題