Vivek Shankar Vivek Shankar - 3 months ago 7
C Question

How to extract multi-digit numbers from a string?

Firstly, I know similar questions have been asked before but I believe my case is different.

My input string is:


(5,7) (1,6) (2,4) (10,14) (8,9)


I wrote the following code for extraction into an array.

main(){
char s[100];
int i=0,x,n=0;
int a[20];
printf("Enter the sets:");
gets(s);
x=strlen(s);
while(i<x){
if((s[i]=='(' && s[i+2]==',') || (s[i]==',' && s[i+2]==')'))
{
a[n]=s[i+1]-'0';
n++;
}
i++;
}
for(i=0;i<n;i++){
printf("%d\n",a[i]);
}
}


The output I get is:


5 7 1 6 2 4 8 9


I understand why my code will skip numbers having 2 or more digits.
Please suggest some minor changes to the present code to fix this limitation.

P.S.- I'm looking for a solution which doesn't depend on length of the number.

rht rht
Answer

If the input is in the exact format as in the question, then you can add two loops inside the main while loop to read one set at a time.

while (i < x)
{
    if (s[i] == '(')
    {
        // temporary var to store number
        int num = 0;

        // read first number
        while (s[++i] != ',')
            num = num*10 + s[i]-'0';
        a[n++] = num;

        num = 0;
        // read second number
        while (s[++i] != ')')
            num = num*10 + s[i]-'0';
        a[n++] = num;
    }
    i++;
}