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

I want to store each number into an int variable and then print it out.

For example the output becomes like this.

Value1 = 1

value2 = 5

Value3= 95

value4 = 255

And I want to do this inside a loop, so If I have more than 4 values in strings, I should be able to get the rest of the values.

I would like to see an example for this one. I know this is very basic to many of you, but I find it a little challenging.

Thank you

Ammar
  • 1,203
  • 5
  • 27
  • 64

3 Answers3

11

Modified from cplusplus strtok example:

#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;
}
shantanu pathak
  • 2,018
  • 19
  • 26
gongzhitaao
  • 6,566
  • 3
  • 36
  • 44
0

I don't know the functions mentioned in the comments above but to do what you want in the way you are asking I would try this or something similar.

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);
} 
Edward Goodson
  • 302
  • 1
  • 11
0

If you don't have a modifiable string, I would use strchr. Search for the next , and then scan like that

#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
iain
  • 5,660
  • 1
  • 30
  • 51