在c中从用户获取int到数组

时间:2018-03-23 19:08:10

标签: c

我正在尝试从用户那里得到一组int,我确实检查了非法输入,除了最后一次输入外,它的工作正常:

int *array=(int*)malloc(sizeof(int)*size);

例如,对于大小为3,假设输入为3 5 2.2

因此,当我将数字分配到数组中时,最后一个输入(2.2)被视为2,程序会继续,即使它不应该。

有什么想法吗? 谢谢。

2 个答案:

答案 0 :(得分:1)

与您使用malloc()无关。相反,您需要检查解析输入的方式。一个非常幼稚的解析器只会将2.2作为2读取,并在末尾添加一些额外的垃圾。例如,scanf()就是这样。

您可以轻松测试:

#include <stdio.h>
void main(void) {
  int i;
  scanf("%d",&i);
  printf("%d\n",i);
}

输入小数,例如4.2,你会得到什么? 4 - 最后.2发生了什么?实际上,它还在输入缓冲区中等待读取它。

您必须使用更智能的扫描仪来验证用户是否输入了垃圾。

答案 1 :(得分:1)

正如上面提到的 PaulProgrammer ,您必须使用更智能的scanner来验证用户是否输入了垃圾。您可以使用character reader扫描仪然后检查如果用户输入的值是integer或不是int,则检查某些特征,如果属于integer,只需使用atoi()等函数将字符串转换为 #include <stdio.h> #include <stdlib.h> int main() { char ch,arr[20]; //arr is an array for storing the character values initially taken as input. int x,input[100],i=0,count=0; //input is an array which will hold the integer values while((x=scanf("%c",&ch))>0){ if(ch=='.') //checking if there is any floating point number { printf("Wrong Input"); return 0; } if(ch>='0' && ch <='9') //check if ch is in the range of 0-9 { arr[i++]=ch; } if(ch==' ' || ch=='\n'){ arr[i]='\0'; input[count++]=atoi(arr); i=0; } if(count==7) break; } for(int loop=0;loop<6;loop++){ printf("%d ",input[loop]); } } ,否则输出向用户发出警告。

我为你写了一个小代码,它需要6个整数并检查浮点数和其他错误值。

{{1}}

我希望你明白这一点。请注意,当你编写这段代码时,请确保它检查每个可能的输入错误。