6
Char *strings = "1,5,95,255"

我想将每个数字存储到一个 int 变量中,然后将其打印出来。

例如输出变成这样。

值 1 = 1

值2 = 5

值 3= 95

值4 = 255

而且我想在循环中执行此操作,因此如果字符串中有 4 个以上的值,我应该能够获得其余的值。

我想看一个例子。我知道这对你们中的许多人来说是非常基础的,但我觉得它有点挑战性。

谢谢

4

3 回答 3

10

cplusplus strtok示例修改:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main ()
{
    char str[] ="1,2,3,4,5";
    char *pt;
    pt = strtok (str,",");
    while (pt != NULL) {
        int a = atoi(pt);
        printf("%d\n", a);
        pt = strtok (NULL, ",");
    }
    return 0;
}
于 2013-04-04T22:17:40.863 回答
0

我不知道上面评论中提到的功能,但是按照你要求的方式做你想做的事,我会尝试这个或类似的东西。

char *strings = "1,5,95,255";
char number;
int i = 0; 
int value = 1;

printf ("value%d = ", value);
value++; 

while (strings[i] != NULL) {
   number = string[i];
   i++;
   if (number == ',') 
       printf("\nvalue%d = ",value++);
   else 
       printf("%s",&number);
} 
于 2013-04-04T22:27:37.910 回答
0

如果您没有可修改的字符串,我会使用strchr. 搜索下一个,,然后像这样扫描

#define MAX_LENGTH_OF_NUMBER 9
char *string = "1,5,95,255";
char *comma;
char *position;
// number has 9 digits plus \0
char number[MAX_LENGTH_OF_NUMBER + 1];

comma = strchr (string, ',');
position = string;
while (comma) {
    int i = 0;

    while (position < comma && i <= MAX_LENGTH_OF_NUMBER) {
        number[i] = *position;
        i++;
        position++;
    }

    // Add a NULL to the end of the string
    number[i] = '\0';
    printf("Value is %d\n", atoi (number));

    // Position is now the comma, skip it past
    position++;
    comma = strchr (position, ',');
}

// Now there's no more commas in the string so the final value is simply the rest of the string
printf("Value is %d\n", atoi (position)l
于 2013-04-04T22:55:38.937 回答