2016-11-30 62 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; 
}