c - fgets 限制输入长度

标签 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);

最佳答案

检查使用 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();

关于c - fgets 限制输入长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28574983/

相关文章:

c - 在 Linux 编程中通过管道在进程之间发送链表结构的最佳方法是什么

c - 我的函数的时间复杂度是多少?

关于 C 中位域排序语义的澄清

c - 您将如何接收与 'sendfile' 一起发送的文件?

c - 从 IP 地址 C 获取主机

c - 指向空函数的指针

c - 给定一个长字符串数组,如何有效地检查给定的子字符串对(给定字符串)是否最多相差一个字符?

c - 在 C 中获取当前时间/日期/日期的最有效方法

计算斐波那契数列的第 n 个数,其中 n 在命令行中输入

c - 在 c 中分配数据的问题