1

我需要编写一个函数来验证用户在 gtk 输入字段中键入的设备名称。

设备必须采用以下形式:

"/dev/video + one digits" ( e.g. /dev/video1 ) 

为此,我创建了函数,但我现在不知道如何编写条件

void validate_device_cb (GtkEntry* entry, const gchar* text,
                         gint length, gint* position, gpointer data)
{
    GtkEditable *editable = GTK_EDITABLE (entry);
    int i, count = 0;
    gchar *result = g_new (gchar, length);

    for (i = 0; i < length; i++) {
            /* insert condition here */

                    continue;
            result[count++] = text[i];
    }

    if (count > 0) {
            g_signal_handlers_block_by_func (G_OBJECT (editable),
                            G_CALLBACK (validate_device_cb), data);
            gtk_editable_insert_text (editable, result, count, position);
            g_signal_handlers_unblock_by_func (G_OBJECT (editable),
                            G_CALLBACK (validate_device_cb), data);
    }
    g_signal_stop_emission_by_name (G_OBJECT (editable), "insert_text");

    g_free (result);
}

欢迎任何帮助

更新(更多解释)

gtk 条目必须只接受输入的这个字符:

first typed: '/'
second       'd'
third        'e'
fourth       'v'
fifth        '/'
sixth        'v'
seventh      'i'
eight        'd'  
.........
eleven        digit
twelve        digit

设置设备入口:

video_device = gtk_entry_new_with_max_length(12);
gtk_editable_set_editable(GTK_EDITABLE(video_device),TRUE);
g_signal_connect(G_OBJECT(video_device), "insert_text" ,
                          G_CALLBACK(validate_device_cb), NULL);
4

1 回答 1

1

一种解决方案是检查字符串是否以/dev/video( strstr) 开头,然后检查后面的字符strlen('/dev/video')是否都是数字 ( isdigit)。

更好的解决方案是使用sscanf和格式说明符重新读取字符串,并检查是否所有格式说明符都已匹配。

示例:请参阅以下代码,它测试 4 个字符串、、a和是否具有所需的格式:bcd

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char a[] = "/dev/video42";
    char b[] = "a random string";
    char c[] = "/dev/video"; /* no number at the end */
    char d[] = "/dev/video/something_else";

    /* test variables */
    int n;
    int result;

    /* test for a */
    result = sscanf(a, "/dev/video%d", &n);
    printf("Result for a=%d\n", result);

    /* test for b */
    result = sscanf(b, "/dev/video%d", &n);
    printf("Result for b=%d\n", result);

    /* test for c */
    result = sscanf(c, "/dev/video%d", &n);
    printf("Result for c=%d\n", result);

    /* test for d */
    result = sscanf(d, "/dev/video%d", &n);
    printf("Result for d=%d\n", result);

    return 0;
}

输出是:

Result for a=1
Result for b=0
Result for c=-1
Result for d=0

仅当输出是1字符串格式正确时(因为恰好匹配了一个格式说明符,并且恰好一个在/dev/video%d模式中sscanf

于 2013-09-08T23:53:15.173 回答