sscanf

This is a discussion on sscanf within the C Programming forums, part of the General Programming Boards category; i know you can split strings using strtok.. but i was wondering if it was possible using sscanf.. but the ...

  1. #1
    Registered User
    Join Date
    Jul 2004
    Posts
    91

    sscanf

    i know you can split strings using strtok..
    but i was wondering if it was possible using sscanf..

    but the trick is that i dont know how many tokens there will be in the string..
    eg str = "hi there this is cool"
    and i want it to print
    hi
    there
    this
    is
    cool

    i've tried a while loop but it gets stuck on the first word infinetley
    hi
    hi
    hi
    ....

    ??? any ideas?

  2. #2
    Registered User
    Join Date
    Apr 2004
    Posts
    21
    Do you need to store the strings or just print them out ? If just printing them out you dont really need to use sscanf.

    How about something like this :

    Code:
    #include <stdio.h>
    
    void split_up(char *string, char delimiter)
    {
      for( ; *string != '\0' ; string++ )
      {
        if( *string == delimiter ) printf("\n");
        else printf("%c", *string);
      }
    }
    
    int main(void)
    {
      char string[] = "This is a test";
    
      split_up(string, ' ');
    
      return 0;
    }
    Does this help ?

    Stan

  3. #3
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,592
    Use the "%n" conversion to tell you how many characters have been processed

    Something like
    Code:
    char *p = str;
    int n;
    while ( sscanf( p, "%s%n", word, &n ) == 1 ) {
      printf( "word=%s\n", word );
      p += n;
    }
    Note: %n does NOT increment the return result of sscanf()
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sscanf and string handling question
    By ursula in forum C Programming
    Replies: 14
    Last Post: 05-30-2009, 02:21 AM
  2. Problem using sscanf fgets and overflow checking
    By jou00jou in forum C Programming
    Replies: 5
    Last Post: 02-18-2008, 05:42 AM
  3. Problems reading formatted input with sscanf
    By Nazgulled in forum C Programming
    Replies: 17
    Last Post: 05-10-2006, 12:46 AM
  4. sscanf question
    By Zarkhalar in forum C++ Programming
    Replies: 6
    Last Post: 08-03-2004, 07:52 PM
  5. sscanf (I think)
    By RyeDunn in forum C Programming
    Replies: 7
    Last Post: 07-31-2002, 08:46 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21