2016-11-30 64 views
-1

所以我有一個字符數組,並使用fgets將字符串存儲到我的fgets中。我想停止閱讀並提示用戶使用較少的字符再次輸入字符串。我不希望太久的字符串不能被存儲,而只是被遺忘。如果字符太多,請停止閱讀fgets

​​

所以超過50個字符被輸入時,提示要求用戶重新輸入,然後將其存儲在所述字符串,如果其小於或等於50個字符。

+1

'questionLength'看起來像一個數組的麻煩名稱。 – pmg

回答

0

檢查最後一個字符是否是換行符。如果是的話,輸入是好的(你可能想要刪除換行符),否則讀取所有可用的字符直到幷包括下一個換行符(正在讀取錯誤,eof)並重復。

char questionLength[50]; 
tryagain: 
printf("Second can you tell me the question for your answer\n"); 
fgets(questionLength, 50, stdin); 
size_t len = strlen(questionLength); 
if (questionLength[len - 1] != '\n') { 
    int ch; 
    do ch = getchar(); while (ch != '\n'); /* error checking ommited */ 
    goto tryagain; 
} 
1

可以檢查的最後一個字符是questionLength換行符(fgets()將在新行讀取,如果有空間)。如果是這樣,你知道它小於或等於50個字符。 否則,輸入更長。

當輸入是剛好 49字節那麼就不會有換行符。您可以通過再讀一個字符來解決它(更改questionLength大小51)。

0

你會知道整個字符串是否被讀取,因爲它包含一個newline。如果你想放棄任何長字符串的其餘部分,一個簡單的方法是首先閱讀它。如果一次嘗試閱讀,那很好。

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

#define STRLEN 50 

int main(void) 
{ 
    char questionLength[STRLEN+2];   // 1 for newline, 1 for EOS 
    int tries; 

    while(1) { 
     tries = 0; 
     printf("Second can you tell me the question for your answer\n"); 
     do { 
      if(fgets(questionLength, sizeof questionLength, stdin) == NULL) { 
       exit(1); 
      } 
      tries++; 
     } while(strchr(questionLength, '\n') == NULL); 

     if(tries == 1) { 
      printf("You entered: %s", questionLength); 
     } 
     else { 
      printf("Your entry was too long\n"); 
     } 
     printf("\n"); 
    } 
    return 0; 
}