如何在C

时间:2016-01-07 12:32:26

标签: c loops char

我的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 *

修改

此外,还需要考虑以下几点:

  1. 数量范围可以是任意数量。管道中可能有10个或84个或55个。
  2. 我想要index=1 for i=0index=12 for i=1index=23 for i=2等等。

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..
    }
}