Check if user input into an array is too long?

前端 未结 6 2119
执笔经年
执笔经年 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:57

    OP is on the right track, but needs adjust to deal with errors.

    The current approach, using scanf() can be used to detect problems, but not well recover. Instead, use a fgets()/sscanf() combination.

    char line[101];
    if (fgets(line, sizeof line, stdin) == NULL) HandleEOForIOError();
    unsigned arr[4];
    int ch;
    int cnt = sscanf(line, "%1x%1x%1x%1x %c", &arr[0], &arr[1], &arr[2],&arr[3],&ch);
    if (cnt == 4) JustRight();
    if (cnt < 4) Handle_TooFew();
    if (cnt > 4) Handle_TooMany();  // cnt == 5 
    

    ch catches any lurking non-whitespace char after the 4 numbers.
    Use %1u if looking for 1 decimal digit into an unsigned.
    Use %1d if looking for 1 decimal digit into an int.


    OP 2nd approach array[0]=line[0]-'0'; ..., is not bad, but has some shortcomings. It does not perform good error checking (non-numeric) nor handles hexadecimal numbers like the first. Further, it does not allow for leading or interspersed spaces.

提交回复
热议问题