Thread: Sorting words from line-input in an array of strings

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    9

    Sorting words from line-input in an 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. Maybe I'm screwing up with the pointers, I don't know.

    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])) {
    	strcpy(param[paramc], tmp);
    	j = 0;
    	paramc++;
    	}
          else { 
    	tmp[j] = input[i];
    	j++;
          }
        
     }
    printf("%s", param[0]);    // this prints (null), for some reason. Propably obvious to many of you, but unfortunately not to me atm.
    Last edited by duckdace; 10-09-2010 at 07:37 AM.

  2. #2
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    RTM of all the functions you use.
    scanf() %s stops reading when encountered white space. temp is used un-initialized.
    Edit: Your code should crash actually.param is array of pointers. You need to allocate memory.
    Last edited by Bayint Naung; 10-09-2010 at 07:47 AM.

  3. #3
    Registered User
    Join Date
    Oct 2010
    Posts
    9
    Ah, of course. Used fgets, allocated memory, and it seems to work. I have to improve the algorithm a bit, but I believe I can do that without help. Many thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem sorting an array of strings
    By Leojeen in forum C Programming
    Replies: 7
    Last Post: 05-07-2008, 09:02 PM
  2. Creating a menu that reads input via an array?
    By Nalif in forum C Programming
    Replies: 6
    Last Post: 09-29-2006, 09:21 PM
  3. Problem with malloc() and sorting words from text file
    By goron350 in forum C Programming
    Replies: 11
    Last Post: 11-30-2004, 10:01 AM
  4. Reading strings input by the user...
    By Cmuppet in forum C Programming
    Replies: 13
    Last Post: 07-21-2004, 06:37 AM
  5. Sorting strings in an array
    By JLan in forum C Programming
    Replies: 4
    Last Post: 11-29-2003, 05:10 PM