Check if user input into an array is too long?

前端 未结 6 2111
执笔经年
执笔经年 2021-01-24 18:19

I am getting the user to input 4 numbers. They can be input: 1 2 3 4 or 1234 or 1 2 34 , etc. I am currently using

int array[4];
scanf(\"%1x%1x%1x%1x\", &ar         


        
6条回答
  •  时光说笑
    2021-01-24 18:36

    E.g

    #include 
    
    int main(void){
        int array[4], ch;
        size_t i, size = sizeof(array)/sizeof(*array);//4  
    
        i = 0;
        while(i < size){
            if(1!=scanf("%1x", &array[i])){
                 //printf("invalid input");
                 scanf("%*[^0123456789abcdefABCDEF]");//or "%*[^0-9A-Fa-f]"
            } else {
                ++i;
            }
        }
        if('\n' != (ch = getchar())){
            printf("Extra input !\n");
            scanf("%*[^\n]");//remove extra input
        }
        for(i=0;i

提交回复
热议问题