0

I have the following:

char *strings = "1998,9,20,"

Here I want to store each number into an integer varaible and print as :

1998

9

20

I tried using strtok and then atoi but this did not help me as my variable is a character pointer and not an array.

anatolyg
  • 26,506
  • 9
  • 60
  • 134
Shilpa
  • 19
  • 2
  • Arrays decays to pointers to their first element, arrays and pointers can often be used interchangeably. And check out e.g. [this `atoi` reference](http://en.cppreference.com/w/c/string/byte/atoi) and see what argument it actually takes. – Some programmer dude Jun 08 '17 at 10:48
  • I guess you try to pass the `strings` pointer as an argument to `strtok` which will segfault because string literals are stored in read-only memory but `strtok` expects the string to be modifyable. So you *have* to copy the string literal into an array before being able to use it with `strtok`. – zett42 Jun 08 '17 at 11:11

2 Answers2

0

with <regex> library:
and regex_token_iterator as splitter:

unsigned int some_int[ 5 ]{};

const char* string = "1998,9,20,";

const char* begin_s = string;
const char* end___s = string + std::string( string ).size();

std::regex regex( "," );

std::regex_token_iterator< const char* > first( begin_s, end___s, regex, -1 ), last;

unsigned int index = 0;

while( first != last ){
    some_int[ index++ ] = std::stoi( *first++ );
}

for( unsigned int item : some_int ){
    std::cout << item << '\n';
} 

the output:

1998
9
20
0
0
Shakiba Moshiri
  • 21,040
  • 2
  • 34
  • 44
0

Maybe this does what you want to do in a simple way?

const char *strings = "1998,9,20,";
const char *ptr = strings;
while (true) {
    int val;
    val = atoi(ptr);
    ptr = strchr(ptr,',');

    if (ptr == 0)
        break;

    std::cout << val << std::endl;
    ptr++;
} 
Tobi
  • 47
  • 4