当输入的长度超过C字符串数组的大小时,有哪些处理方法?

问题描述 投票:1回答:1

使用C编程语言,

我正在尝试将字符串输入读取并存储到具有固定大小的char数组[11]。

当我输入的字符超过10个时,其余字符将发送到下一个scanf。

所以我的问题是,

  1. 是否有任何方法可以限制输入的大小?

  2. 或者,当输入超过char数组的大小时,有没有办法截断其余字符,而不发送到下一个scanf?

  3. 或者,我应该知道要输入多少个字符?

  4. 或者,我应该创造条件防止发生此问题吗?

int main(void)
{
    char phoneNum[11];
    char password[11];

    printf("Enter the phone Number: ");
    scanf("%10s", phoneNum);

    printf("Enter the password: ");
    scanf(" %10s", password);

    printf("\n\n");
    //Display
    printf("Phone number: %s\n", phoneNum);
    printf("Password : %s\n", password);

    return 0;
}

/*
What I tried: 
-input: 
 Enter the phone Number: 123-456-7890
 Enter the password:    // This part has been skipped.

-output:
 Phone number: 123-456-78
 Password: 90


What I expected:
-input:
 Enter the phone Number: 123-456-7890
 Enter the password: asdf12386945648

-output:
 Phone number: 123-456-78
 Password: asdf123869
*/
c scanf c-strings
1个回答
1
投票

是否有任何方法可以限制输入的大小?

否,代码不能阻止用户键入。相反,代码可以限制保存的输入量,并可能因输入过多而消耗或退出。

或者,当输入超过char数组的大小时,有没有办法截断其余字符,而不发送给下一个scanf?

是。最好不要将其发送到下一个输入函数。在这里处理您的问题。一个简单的解决方案是

int read_input(char *destination, size_t sz) {
  if (sz > INT_MAX) sz = INT_MAX;
  if (fgets(destination, sz, stdin) == NULL) return EOF;
  size_t len = strlen(destination);
  if (len > 0 && destination[len-1] == '\n') { // lop off potential \n
    destination[--len]  = '\0';
  }
  if (len + 1 == sz) {  // if more input ...
    // let us consume it and toss it.
    int ch;
    while ((ch = fgetc(stdin)) != '\n' || ch != EOF) {
      ;
    }
    // Input exceeds expectations, take evasive action.
    // Maybe print an error message and try again?
    // For now, let us just exit.
    fprintf("Input too long\n");
    exit(EXIT_FAILURE);
  }
  return (int) len;
}    

或者,我是否应该知道要键入多少个字符?

用户输入是邪恶的-期望最糟。建议允许最大合法输入量的两倍。除此之外,还有坏事发生。

或者,我应该创造条件来防止此问题吗?

无法阻止,只能处理错误或恶意的输入。


提示:要有足够的预期输入大小。对于11phoneNum[]太小。允许输入处理您可能期望的2倍,例如30then限定输入。疯狂的输入长度是一种攻击。

© www.soinside.com 2019 - 2024. All rights reserved.