Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C编程-检查字符并停止数组长度超过50个字符_C_Arrays_Validation - Fatal编程技术网

C编程-检查字符并停止数组长度超过50个字符

C编程-检查字符并停止数组长度超过50个字符,c,arrays,validation,C,Arrays,Validation,您好,我希望能够在我的结构“数据包”的“数据”条目中输入我的数据时进行一些验证 基本上,它只能是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 structur

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

基本上,它只能是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);

所有帮助都很有用,我提前向您表示感谢。

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


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

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

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

使用以下方法:

scanf("%49s", list[x].data);
您需要49而不是50,因为将添加空终止符

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

使用以下方法:

scanf("%49s", list[x].data);
您需要49而不是50,因为将添加空终止符


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

将目标的大小增加到50个字符和一个
\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();
struct packet{//声明用于创建数据包的结构
...
字符数据[51];
};
//它只能有50个字符长,并且只能有数字输入
如果(scanf(“%50[0-9]”,list[x].data)!=1)处理意外输入();
if(strlen(list[x].data)<50))String_Too_Short();

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

增加目标的大小,以容纳50个
字符和一个
\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();
struct packet{//声明用于创建数据包的结构
...
字符数据[51];
};
//它只能有50个字符长,并且只能有数字输入
如果(scanf(“%50[0-9]”,list[x].data)!=1)处理意外输入();
if(strlen(list[x].data)<50))String_Too_Short();

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

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