View Single Post
  #4  
Old 08-24-2006, 22:54
tom324 tom324 is offline
Friend
 
Join Date: Jan 2002
Posts: 233
Rept. Given: 5
Rept. Rcvd 7 Times in 6 Posts
Thanks Given: 26
Thanks Rcvd at 28 Times in 17 Posts
tom324 Reputation: 7
Check his code. And consider using multidimensional arrays .

Tom

Code:
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
   char  *pi;
   int   i, r, j, len;
   puts("start");
   char tmp_str[50];
   pi = (char*)malloc(50 * sizeof(char));


   if ( pi == NULL )
   {
      /* error handler here */
   }

   memset(pi, 0, 50 * sizeof(char));

   for ( i = 0, len = 0; i < 5; i++ )
   {
      printf("Enter element %d = ", i);
      r = scanf("%s", tmp_str);
      if ( r != 1 )
      {
         break;
      }
      else
      {
         sprintf(&pi[len], "%s ", tmp_str);
         len += strlen(tmp_str) + 1;
      }
   }
   /*-----------------24.08.2006 16:35-----------------
    * pi is one dimensional array holding 5 elements separated by spaces
    *  "a b c d e"
    * --------------------------------------------------*/

   printf("array '%s'\n", pi);

   i = 0;
   len = 0;
   while ( i < 5 )
   {
      j = sscanf(&pi[len], "%s[^ ]", tmp_str);
      if ( j == 1)
      {
         printf("%s", tmp_str);
         len += strlen(tmp_str) + 1;
      }
      putchar('\n');
      i++;
   }

   free(pi);
   puts("Done!");

   return 0;
}
Reply With Quote