我的pipeline
文件中有C
个变量:
const char *pipeline = "1|12|23|34|45|56|67|78|89|90";
static int doWork(char *data, char *res_data) {
for (i = 0; i < strlen(data); i++) {
int index = // here I want to get 1,12,23... as integer to be used as index for my purpose
}
}
我的问题是,如何从1,12,23,...,n
阅读char *
?
修改
此外,还需要考虑以下几点:
index=1 for i=0
,index=12 for i=1
,index=23 for i=2
等等。答案 0 :(得分:3)
如果pipeline
允许char[]
而不是char *
,则此方法有效:
#include <stdio.h>
#include <string.h>
int main ()
{
char pipeline[] = "1|12|23|34|45|56|67|78|89|90";
char * pch;
pch = strtok (pipeline,"|");
int num;
while (pch != NULL)
{
sscanf (pch,"%d",&num);
printf("%d\n",num);
pch = strtok (NULL, "|");
}
return 0;
}
此外,您可以:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
char *pipeline = "1|12|23|34|45|56|67|78|89|90";
char *pch=pipeline;
while (*pch)
{
int index=strtol(pch,&pch,10);
printf("%d\n",index);
if(*pch=='|')
pch++;
}
return 0;
}
答案 1 :(得分:1)
鉴于您的pipeline
格式,我想这就是您所需要的:
for (i = 0; i < strlen(data); i++) {
int j;
if( ( i % 2 ) == 0 )
{
j = *(data + i) - '0'; // j = 1,2,3 and so on..
}
}