Thread: Pulling words from a char buffer

  1. #1
    Registered User
    Join Date
    Jan 2022
    Posts
    7

    Question Pulling words from a char buffer

    I'm just learning c and I barely understand what I'm doing. I have a buffer and I want to chop a word off the front, one at a time and then do something with it. Guess, I need a pointer to the buffer and be able to move it around and do I need to free anything? Cause, eventually, I'll have a while loop getting input from the user, taking the input, and chopping it up into words.

    Code:
    #include <stdio.h>
    #include <string.h>
    
    
    void pull_word(char *cmd, char delim) {
      int i = 0;
      
      for (i = 0; i < strlen(cmd); i++) {
          if (cmd[i] == delim) break;
          printf("%c", cmd[i]);
      }
    }
    
    
    char *buffer = "ls a b c";
    
    
    int main()
    {
        pull_word(buffer, ' '); //would print ls a b c
        
        pull_word(buffer, ' '); //would print a b c
    
    
        return 0;
    }

  2. #2
    Registered User
    Join Date
    Dec 2017
    Posts
    1,633
    Code:
    #include <stdio.h>
     
    char *pull_word(char *cmd, char delim) {
        puts(cmd);
        char *p = cmd;
        for ( ; *p != '\0' && *p != delim; p++)
            ;
        while (*p == delim) ++p;
        return p;
    }
     
    int main()
    {
        char *buffer = "ls a b c";
        for (char *p = buffer; *p; )
            p = pull_word(p, ' ');
        return 0;
    }
    A little inaccuracy saves tons of explanation. - H.H. Munro

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Char Buffer
    By RocketMan46 in forum C Programming
    Replies: 7
    Last Post: 04-29-2016, 11:53 PM
  2. how to know if there is some char in the buffer..
    By transgalactic2 in forum C Programming
    Replies: 30
    Last Post: 01-30-2009, 03:27 PM
  3. taking some words out of buffer
    By apsync in forum C Programming
    Replies: 1
    Last Post: 02-26-2005, 06:32 AM
  4. Using a *char Buffer
    By Hankyaku in forum C++ Programming
    Replies: 2
    Last Post: 04-13-2003, 01:49 AM
  5. Words waiting in input buffer
    By the person in forum C++ Programming
    Replies: 2
    Last Post: 10-09-2001, 09:44 AM

Tags for this Thread