C语言读取字符串中的数字
一、strstr&atoi函数介绍
- strstr
C 库函数 char *strstr(const char *haystack, const char *needle) 在字符串 haystack 中查找第一次出现字符串 needle 的位置,不包含终止符 ‘\0’。
示例程序:
#include <stdio.h>
#include <string.h>
int main()
{
const char haystack[20] = "RUNOOB";
const char needle[10] = "NOOB";
char *ret;
ret = strstr(haystack, needle);
printf("子字符串是: %s\n", ret);
return(0);
}
运行结果:子字符串是: NOOB
- atoi
C 库函数 int atoi(const char *str) 把参数 str 所指向的字符串转换为一个整数(类型为 int 型)。
示例程序:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int val;
char str[20];
strcpy(str, "98993489");
val = atoi(str);
printf("字符串值 = %s, 整型值 = %d\n", str, val);
strcpy(str, "runoob.com");
val = atoi(str);
printf("字符串值 = %s, 整型值 = %d\n", str, val);
return(0);
}
运行结果:
字符串值 = 98993489, 整型值 = 98993489
字符串值 = runoob.com, 整型值 = 0
二、结合使用
/* parse roi option*/
// format: "r0:0:0:0:0:0:0:0;r1:0:0:0:0:0:0:0"
static int get_roi(char *str, RoiParas *roi_paras) {
char *p = str;
unsigned int cnt = 0;
RoiAttr *roi_attr = NULL;
if (!str || !roi_paras) return -1;
while ((p = strstr(p, "r")) != NULL) {
roi_attr = &roi_paras->roi_attr[cnt];
// index
roi_attr->index = atoi(p + 1);//0
// enable
if ((p = strstr(p, ":")) == NULL) return -1;
p++;
roi_attr->enable = atoi(p);
// absQp
if ((p = strstr(p, ":")) == NULL) return -1;
p++;
roi_attr->is_absQp = atoi(p);
// qp
if ((p = strstr(p, ":")) == NULL) return -1;
p++;
roi_attr->qp = atoi(p);
// left
if ((p = strstr(p, ":")) == NULL) return -1;
p++;
roi_attr->left = atoi(p);
// top
if ((p = strstr(p, ":")) == NULL) return -1;
p++;
roi_attr->top = atoi(p);
// right
if ((p = strstr(p, ":")) == NULL) return -1;
p++;
roi_attr->right = atoi(p);
// bottom
if ((p = strstr(p, ":")) == NULL) return -1;
p++;
roi_attr->bottom = atoi(p);
// num
cnt++;
}
roi_paras->num_of_roi = cnt;
return 0;
}
#typedef struct {
unsigned char index; //index, coresponding with 0 ~ (MAX_ROI_NUM-1)/roi1~roi8 area
unsigned char enable; //1: enable, 0: disable
unsigned char is_absQp; //1: absolute QP, 0: relative QP
char qp; //QP value, if is_absQp == 1, [0, 51]; else [-30, 0]
unsigned int left; //x-coordinate of the upper-left
unsigned int top; //y-coordinate of the upper-left
unsigned int right; //x-coordinate of the lower-right
unsigned int bottom; //y-coordinate of the lower-right
} RoiAttr;
实现从字符串中读取数字。