0

我有这段代码可以从命令中解码输入字符

    if( arg && isdigit( arg[ 0 ] ) {

        /* Decode the input char from commands.  */
        if( cmd->digit_counter == 0 ) memset( cmd->next_chan_buffer, 0, 5 );
        cmd->next_chan_buffer[ cmd->digit_counter ] = arg[ 0 ];
        cmd->digit_counter++;
        cmd->frame_counter = cmd->delay;

        /**
         * Send an enter command if we type more digits than there are stations.
         */
        if( cmd->digit_counter > 0 && (station_get_max_position( cmd->station ) < 10) ) {
            commands_handle( cmd, ENTER, 0 );
        } else if( cmd->digit_counter > 1 && (station_get_max_position( cmd->station ) < 100) ) {
            commands_handle( cmd, ENTER, 0 );
        } else if( cmd->digit_counter > 2 ) {
            commands_handle( cmd, ENTER, 0 );
        }
    }

例如,在键盘上输入数字并在框中输入数字

      |5|4|2|0|

我想防止第一个计数数字为 0(或只接受 1 到 9 的数字)和第二个、第三个、... 数字来接受 0 - 9 的数字

digits count           1            2        3        4
          -------------------------------------------------
          | only digits 1 to 9 | 0 to 9 | 0 to 9 | 0 to 9 |
          -------------------------------------------------

谢谢

好的,通过添加功能解决:

int first_digit( int num ) 
{
        while(num >= 10) {
            num = ( num - ( num % 10 ) ) / 10;
        }
        return num;
}

if( arg && isdigit( arg[ 0 ] ) {

        /* Decode the input char from commands.  */
        if( cmd->digit_counter == 0 ) memset( cmd->next_buffer, 0, 5 );
        cmd->next_buffer[ cmd->digit_counter ] = arg[ 0 ];
        if( first_digit( atoi( cmd->next_chan_buffer ) ) != 0 ) {
            cmd->digit_counter++;
            cmd->frame_counter = cmd->delay;
        }
}
4

1 回答 1

0

您可以像这样执行检查,而不是使用 isdigit()。

if( arg && arg[0] >= '1' && arg[0] <= '9' ) { // only accept '1' through '9'

从 '0' 到 '9' 的字符在 C 中总是以相邻的顺序排列,所以这个检查可以满足你的需要。

于 2013-04-04T19:56:46.333 回答