fgets限制输入长度

时间:2015-02-18 02:31:25

标签: c

当我输入像姓氏这样的数据时,我已将它限制为10个字符,但当我尝试输入姓氏时,从名字中排除的字符将被放入姓氏。例如,如果我输入aaaaaaaaaab,则会保留a,但b将被放入姓氏。

有什么建议我会解决这个问题吗?我希望它将长度限制为正确的数量。

printf("you chose add new record\n"); 
printf("enter the person information: \n");
printf("Please enter the first name: \n");
//limits to size 10
char namein[11];
fgets(namein, 11, stdin);
printf("the first name was: %s\n", namein);

printf("Please enter the last name: \n");
//limits to size 20
char lastin[21];
fgets(lastin, 21, stdin);
printf("the last name was: %s\n", lastin);

2 个答案:

答案 0 :(得分:3)

检查使用fgets()的结果。

如果缓冲区包含\n,则无需查找更多内容。否则,在'\n'EOF之前消耗可能的额外数据。

int ConsumeExtra(const char *buf) {
  int found = 0;
  if (strchr(buf, '\n') == NULL) {
    int ch;
    // dispose of extra data
    while ((ch = fgetc(stdin)) != '\n' && ch != EOF) {
      found = 1;
    }
  }
  return found;
}

char namein[11];
if (fgets(namein, sizeof namein, stdin) == NULL) Handle_EOForIOError();
if (ConsumeExtra(namein)) Handle_ExtraFound(); 

注意:建议输入缓冲区不要太小。最好读入一般的大缓冲区,然后在保存到namein之前限定输入。 IOWs,更喜欢将输入和扫描/解析分开。

char buffer[100]
char namein[11];
if (fgets(namein, sizeof buf, stdin) == NULL) Handle_EOForIOError();
if (ConsumeExtra(buf)) Handle_InsaneLongInput();

int n = 0;
sscanf(buffer, "%10s %n", namein, &n);
if (n == 0 || buf[n]) Handle_NothingOrExtraFound();

答案 1 :(得分:-1)

在进行下一次读取之前,必须先读取整个输入缓冲区。这样的操作被称为"排水"输入。

所以你的代码应该是

get the first name
read the first name
drain the input
print the prompt for the last name
read the last name

耗尽输入看起来大致像

while (there is data that can be read) {
  read a character
}
相关问题