how to split input string into 4 components

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nyc680
    New Member
    • Mar 2009
    • 3

    how to split input string into 4 components

    Sample input string

    james 35 bond 30
    berry 40 bond 37

    The program must separte each line into 4 parts. first name, age, last name, and age+7, the following code is a sample of with only 2 component, I don't know how to do it with 4 components. Could someone edit the code for me please.



    Code:
    void main(int argc, char *argv[])
    {
    	struct person list[];
    	int i,n;
    	char *ch, *ch1;
    	char buf[256];
    	FILE *file1;
    	i=0;
    	fgets(buf,250,file1);    
    
    	while(!feof(file1))
    	{
    	ch=strchr(buf,'\n');
    	if (ch!=NULL) *ch='\0';
    	else break;
    	ch = strchr(buf, ' ');
    	if(ch!=NULL) 
                     { 
                     *ch='\0'; 
                     ch1=++ch;  //age
                 
                      }
    	else break;
    	strcpy(list[i].lastname,buf);
                    list[i].age=atoi(ch1);
    	i++;		
    	fgets(buf,256,file1);
    	}
    
    	n=i;
    	for(i=0;i<n;i++)
                  printf("%s is %d years, first name is %s\n", list[i].lastname, list[i].age); 
        }
  • gpraghuram
    Recognized Expert Top Contributor
    • Mar 2007
    • 1275

    #2
    Hi,
    If the lines are tokens are separated by space then u can use this logic.
    Open the file
    Read the line using fgets.
    use sscnaf to read the 4 values
    store the values
    close the file

    Thanks
    Raghu

    Comment

    • nyc680
      New Member
      • Mar 2009
      • 3

      #3
      do sscanf automatically parse into 4 parts? can you show me an example code?

      Comment

      • gpraghuram
        Recognized Expert Top Contributor
        • Mar 2007
        • 1275

        #4
        hi,
        Check this.

        [code=cpp]
        int arr[]="james 35 bond 30";
        char val1[10],val3[2];
        int val2,val4;

        sscanf(arr,"%s %d %s %d",val1,&val2, val3,&val4);

        [/code]

        I think the above one helps u.

        Raghu

        Comment

        Working...