【问题标题】:C Programming - Check for characters and stop the array being over 50 chars longC 编程 - 检查字符并停止长度超过 50 个字符的数组
【发布时间】:2013-12-15 03:19:56
【问题描述】:

您好,我希望能够在我的结构“数据包”的“数据”条目中输入我的数据时进行一些验证。

基本上它只能是 50 个字符长并且只有数字输入。

struct packet{ // declare structure for packet creation
    int source;
    int destination;
    int type;
    int port;
    char data[50];
};

struct packet list[50]; //Array for structure input & initiate structure 

printf("\nEnter up to 50 numeric characters of data.\n");
scanf("%s", list[x].data);

所有帮助都是有用的,我提前感谢您。

【问题讨论】:

  • 是什么阻止你编写这样的代码?究竟有什么困难?
  • 我目前在大学学习 C,所以我对 C 语言的效率不是 100%。我有自己想做的想法,但不知道如何去做。

标签: c arrays validation


【解决方案1】:

使用这个:

scanf("%49s", list[x].data);

您需要 49 而不是 50,因为会添加一个空终止符。

获得字符后,使用 isdigit() 执行有效性检查。

【讨论】:

    【解决方案2】:

    增加目的地的大小以容纳 50 char\0。使用格式 "%50[0-9]" 说明符。

    struct packet{ // declare structure for packet creation
      ...
      char data[51];
    };
    // it can only be 50 characters long and only have number inputs
    if (scanf("%50[0-9]", list[x].data) != 1) Handle_Unexpected_Input();
    if (strlen(list[x].data) < 50)) String_Too_Short();
    

    您可能需要前导空格来丢弃前导空格:" %50[0-9]"

    【讨论】:

      【解决方案3】:

      您正在寻找避免缓冲区溢出的方法。有很多方法可以做到这一点。

      Here is one example using snprintf

      Here is another example using a length-limiting format string.

      要验证数组中的所有字符(如果它们以 ASCII 编码)都是数字,您必须遍历每个字符并验证每个字符的整数值是否在 48 和 57 之间('0' - '9')。

      【讨论】:

        猜你喜欢
        • 2021-05-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-03
        • 2016-07-22
        • 1970-01-01
        相关资源
        最近更新 更多