Thread: strings with sscanf...

  1. #1
    Registered User
    Join Date
    Nov 2006
    Posts
    6

    strings with sscanf...

    I have a text file that I need to read. The file consists of 3 fields that I need to store. The first is a label of words separated by spaces, the second and third are just one word of text each. I want to use sscanf to process each line.

    Please see the attached text file for an example of the format:

    My question is this: How can I handle the first field using sscanf? I think I know how to handle th etwo other fields since they are just one word each..but the first field can be one or many words (no more than 20 characters in total length).

    Thanks in advance!

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    Maybe "%20[^\n]"
    Which should be 20 characters of anything which isn't a newline.

    Though if you know the field widths, building something using strncpy() would be better.
    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.

  3. #3
    Registered User
    Join Date
    Nov 2006
    Posts
    6
    I was using this to read the two one word text fields
    sscanf( p, "%s %s%n", text1, text2, &n);
    Now the variable length field has been added to the beginning of each line as I have shown in the example.txt file.

    By implementing your suggestion would this work?

    Code:
    sscanf( p, "%20[^\n] %s %s%n", label, text1, text2, &n);

  4. #4
    Registered User
    Join Date
    Nov 2006
    Posts
    6
    That worked. Thank you! Plus I read up on it in the unix man pages and now what they say makes a little more sense.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. reading strings with spaces using sscanf
    By kotoko in forum C Programming
    Replies: 2
    Last Post: 06-14-2008, 05:06 PM
  2. sscanf and parsing strings
    By jco1323 in forum C Programming
    Replies: 4
    Last Post: 02-20-2008, 06:32 PM
  3. Strings Program
    By limergal in forum C++ Programming
    Replies: 4
    Last Post: 12-02-2006, 03:24 PM
  4. Programming using strings
    By jlu0418 in forum C++ Programming
    Replies: 5
    Last Post: 11-26-2006, 08:07 PM
  5. Reading strings input by the user...
    By Cmuppet in forum C Programming
    Replies: 13
    Last Post: 07-21-2004, 06:37 AM