Words from keyboard to array of strings

duckdace's Avatar, Join Date: Oct 2010
Light Poster
Hi.

My intention is to receive input from keyboard, preferably a sentence(or a command with args, for that matter) with words divided by a space, and then store each of these words as an element in an array. This is my effort so far, but I don't seem to be able to make it work the way I want.

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

   char input[200];  
   char *param[5];   //array of the strings
   int i;
   int paramc = 0;    //wordcounter
   char tmp[50];  
   int j = 0;

printf("Say something");
scanf("%s", input);

 for (i=0; i< strlen(input); i++) {
      
      if (isspace(input[i])) {
        param[paramc] = malloc(strlen(tmp));
    strcpy(param[paramc], tmp);
    j = 0;
    paramc++;
    }
      else { 
    tmp[j] = input[i];
    j++;
      }
    
 }
printf("%s", param[0]);    // this prints (null)
duckdace's Avatar, Join Date: Oct 2010
Light Poster
Nvm. Found out that using scanf is unclever as it stops with whitespace. Changed the code implementing fgets, and it worked.
shabbir like this