Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,971 questions

51,913 answers

573 users

How to add the numbers in string to int array with C

1 Answer

0 votes
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>

#define SIZE 6
 
void remove_all_spaces(char *s) {
    const char *p = s;
    do {
        while (*p == ' ') {
            p++;
        }
    } while ((*s++ = *p++));
}  
   
void add_numbers_to_array(char s[], int arr[]) { 
    char *tmp = strdup(s);
    remove_all_spaces(tmp);
    int i = 0, num = 0;
       
    char *p = tmp;
    while (*p) {
        if (isdigit(*p)) {
            num = num * 10 + strtol(p, &p, 10);
        } 
        else {
            p++;
            arr[i++] = num;
            num = 0;
        }
    }
    if (isdigit(s[strlen(s) - 1]))
        arr[i++] = num;
 
    free(tmp);
} 
     
int main() 
{ 
    char s[] = "1, 6472, 7, 9, 12, 899";
	int arr[SIZE];
 
	add_numbers_to_array(s, arr);
	
	for (int i = 0; i < SIZE; i++)
		printf("%d\n", arr[i]);
     
    return 0; 
} 
   
 
 
      
/*
run:
       
1
6472
7
9
12
899
  
*/

 



answered Jul 2, 2020 by avibootz

Related questions

1 answer 103 views
1 answer 105 views
1 answer 158 views
1 answer 185 views
185 views asked May 24, 2019 by avibootz
1 answer 97 views
...