gpt4 book ai didi

c - 验证在 gtk_entry 中输入的字符串的格式

转载 作者:太空宇宙 更新时间:2023-11-04 03:53:54 24 4
gpt4 key购买 nike

我需要编写一个函数来验证用户在 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);

最佳答案

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

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

示例:请看下面的代码,它测试是否有 4 个字符串,abcd 具有所需的格式:

#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 中的模式)

关于c - 验证在 gtk_entry 中输入的字符串的格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18689557/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com