我是低级编程的新手,一直遇到以下问题:
我得到以下格式的字符串:
?cmd=ASET&<hour>&<minute>
其中小时和分钟值始终由 2 个十进制数组成。 所以可以接收的字符串的例子是:
"?cmd=ASET&08&30"
我正在尝试编写一个 if 语句来识别字符串以“?cmd=ASET”开头并将两个名为分钟和小时的全局变量更改为字符串中的值。我一直在尝试使用 strtok() 执行此操作,但到目前为止还没有任何运气。所以我的 if 语句的全局布局是:
if (String starts with "?cmd=ASET") {
minute = value found in the string;
hour = value found in the string;
}
如果有任何帮助,我将不胜感激。
最佳答案
尝试这样的操作,其中 cmd 是一个 char * 或 char [] 类型的变量。请注意,strncmp()
比 strcmp()
更安全。通常,在 C 编程中,您希望使用限制长度的函数变体,以避免堆栈溢出攻击和其他安全风险。如果输入错误,字符串到数字函数可能会失败,因此最好使用一种可以检查其状态的表单,这就是为什么 atoi()
和 atol()
不推荐。 sscanf()
允许像 strtol()
一样检查状态,因此它们都是可接受的。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int
main()
{
char *string = "?cmd=ASET&12&30";
#define ASET_CMD "?cmd=ASET"
int hour = 0, minute = 0;
if (strncmp(string, ASET_CMD, strlen(ASET_CMD)) == 0) {
if (sscanf(string + strlen(ASET_CMD), "&%d&%d", &hour, &minute) != 2) {
printf("Couldn't parse input string");
exit(EXIT_FAILURE);
}
}
printf("hour: %d, minute: %d\n", hour, minute);
return(EXIT_SUCCESS);
}
$ cc -o prog prog.c
$ ./prog
hour: 12, minute: 30
关于c - 如何比较 C 字符串中的子字符串和解析数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29420564/