Lois Anne Leal Lois Anne Leal - 29 days ago 8
C Question

How to get the tuple form out of the one line input?

I got a code below.
If the user input

(12,34,56,78),(1,2,3)
,

it will only output:
12,34,56,78,1,2,3


but I need to output
(12,34,56,78) (1,2,3)


what should I do?

#include <string.h>
#include <stdio.h>

int main(){
char enter[100];
int a;

printf("Enter a string:");
scanf("%s",enter);
char *tuples=strtok(enter,"()");
while(tuples!=NULL){
printf("%s",tuples);
tuples=strtok(NULL,"()");
}

}

Answer Source

strchr() is an additional parsing tool that may help you. It provides a method to quickly locate a specific character within a string, and return a pointer to that location. This capability, along with sprintf() can be used to reconstruct the string without the middle ",". Following is an illustration.

int main(void)
{
    char string[40] = {"(12,34,56,78),(1,2,3)"};
    char *ret;
    int len1,len2;
    char *first = strdup(string);//a 2nd copy is needed to preserve the 1st half of string.
    char last[20];

    len1 = strlen(string);

    //in your example, the ')' character is the closest unique char to the 
    //target ',', so select this unique character to get close...
    ret = strchr(string, ')');//brings pointer to first ')'
    ret += 2; //increment pointer past next occurring "," to get second half of string
    strcpy(last, ret);

    len2 = strlen(last);
    first[len1-(len2+1)] = 0;//use length information to get first half

    sprintf(string, "%s %s", first, last); 
    printf(string);                 
    free(first);

    return 0;
}

Outputs:

(12,34,56,78) (1,2,3)

A note on user input:
It occurred to me that legal syntax (you have stated no rules) for this seemingly simple scenario can easily result in variations that will make a general solution for parsing and string re-construction difficult. eg, input could be any of the following:

(12,34,56,78),(1,2,3)  
( 12 , 34 , 56 , 78 ) , ( 1 , 2 , 3 )  
(12,34,56,78)      ,       (1,2,3)  
(and many more)    

Keep in mind, to build a general approach to handling user input, the complexity of the code needed to process the input will be inversely proportional to the bounds (rules) put on input. i.e. if there are zero rules, the complexity will be infinite. If there are many rules governing allowed input, the complexity of the code will be proportionally smaller.

A good example of unbounded input is the way people talk. There is very little convention followed in the way people choose to convey their thoughts. (natural language is similar in it variations to user input) A few examples illustrating the complexity needed to process natural language are listed here.

(The input rules in your post are not clearly stated, so any attempt at a trivial solution here, will not likely satisfy any but those with input having syntax similar to your example)