1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Words from keyboard to array of strings

Discussion in 'C' started by duckdace, Oct 9, 2010.

  1. duckdace

    duckdace New Member

    Joined:
    Oct 9, 2010
    Messages:
    9
    Likes Received:
    1
    Trophy Points:
    0
    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)
    
     
  2. duckdace

    duckdace New Member

    Joined:
    Oct 9, 2010
    Messages:
    9
    Likes Received:
    1
    Trophy Points:
    0
    Nvm. Found out that using scanf is unclever as it stops with whitespace. Changed the code implementing fgets, and it worked.
     
    shabbir likes this.

Share This Page