2012-12-02 47 views
1

所以我有這樣的scanf掃描字符串時,如果用戶輸入超過30個字符,該如何禁止輸入?

scanf ("%30[^\n]%c", &i 

我如何添加其中,如果用戶輸入超過30個字符,它會提示一個消息,說有太多的人物,並讓他們重新進入的條件?

這裏是我的整個循環不斷重新進入,直到輸入正確的,但我沒有合適的條件設定

int keeptrying = 1, rc; 
char after, i; 

do 
{ 
    rc = scanf ("%30[^\n]%c", &i, &after); 
     if (rc == 0) 
     { 
      printf (" **Invalid input try again: "); 
      clear(); 
     } 
      else if (after != '\n') 
      { 
       printf (" **Trailing characters try again: "); 
       clear(); 
      } 
       else if() // THIS IS WHERE I WOULD PUT THE CONDITION 
       { 
        printf (" **Title is longer than 30 characters: "); 
       } 
        else 
        { 
         keeptrying = 0; 
        } 

} while (keeptrying == 1); 

return i; 
+1

['strlen的()'](http://pubs.opengroup.org/onlinepubs/009695399/functions/strlen.html) – 2012-12-02 18:50:13

+0

存儲最多30個字符加結尾空成'i'是*糟糕的主意™*。你需要'我'是至少31個字符的數組。 –

回答

1

基本上,你只是想在一條線上閱讀,並檢查如果其長度大於30要做到這一點,您可以使用strlen(),在線閱讀我建議使用類似getline代替:

int keeptrying = 1; 
char *line = NULL; 
size_t linecap = 0; 

do { 
    ssize_t rc = getline(&line, &linecap, stdin); 
    if (rc == 0) 
    { 
     printf ("End of file."); 
     exit(1); 
    } 
    else if (strlen(line) > 30) 
    { 
     printf (" **Title is longer than 30 characters: "); 
    } 
    else 
    { 
     keeptrying = 0; 
    } 
} while (keeptrying == 1); 

// Use line 

free(line); 
+0

哦,忘記了strlen!謝謝 – albert

+1

getline是沒有C標準 – user411313

+0

是啊試過後,它不工作...經過一番研究後,你給我的一些代碼在C – albert

1

可以scanf函數後使用的getchar(也明確標準輸入) :

do 
{ 
    char i[31]; 
    rc = scanf ("%30[^\n]", &i); 
     if (rc == 0) 
     { 
      printf (" **Invalid input try again: "); 
      clear(); 
     } 
      else if (getchar() != '\n') 
      { 
       printf (" more than 30 characters try again: "); 
       clear(); 
      } 
        else 
        { 
         keeptrying = 0; 
        } 

} while (keeptrying == 1); 
相關問題