Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Words from keyboard to array of strings (http://www.go4expert.com/forums/words-keyboard-array-strings-t23534/)

duckdace 9Oct2010 19:38

Words from keyboard to array of strings
 
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 9Oct2010 19:46

Re: Words from keyboard to array of strings
 
Nvm. Found out that using scanf is unclever as it stops with whitespace. Changed the code implementing fgets, and it worked.


All times are GMT +5.5. The time now is 02:04.