Thread: How to read a word between two spaces?

  1. #1
    Registered User
    Join Date
    Sep 2008
    Posts
    26

    Question How to read a word between two spaces?

    Hi all:

    I have assigned a task to basically process a text file. One typical line of text in the file is shown below:

    long custid - 4 - 12 "no bugs"

    There are 7 fields in total:
    1: long
    2: custid
    3: -
    4: 4
    5: -
    6: 12
    7: "no bugs"


    I need to read out each of the field individually.

    How do I start?

    Cheers

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    The only problem presumably is field 7? Or might field 2 have spaces in it too? You could just read in the first six fields, and then the rest of the line would have to be field 7.

    Edit: Or you could use scansets instead of %s to get field 7 too. You'd have to add the quotes back yourself, though.

  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Typically, when parts of the input is wrapped in delimiters ("..." in this case), then you need to read the input either as a long line and separate the line in your code, or read a character at a time, keeping track of what happens in each special case. Something like this:
    Code:
       read a character. 
       case space:
          terminate this field
          field ++
       case quote:
         do 
            read next character
            if (!quote) put character into field. 
         while(!quote)
         terminate field
         field++
       case newline:
          terminate current field
          new set of fields 
          reset field
       default:
          if (valid character) 
             insert into current field. 
          else 
             produce error.
    --
    Mats
    Last edited by matsp; 09-14-2008 at 03:40 AM.
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. bytes lost with partial read in UDP
    By mynickmynick in forum Networking/Device Communication
    Replies: 3
    Last Post: 03-31-2009, 02:06 AM
  2. seg fault at vectornew
    By tytelizgal in forum C Programming
    Replies: 2
    Last Post: 10-25-2008, 01:22 PM
  3. Random word problem
    By goron350 in forum C++ Programming
    Replies: 2
    Last Post: 05-14-2005, 03:44 PM
  4. finding strings in strings
    By watshamacalit in forum C Programming
    Replies: 14
    Last Post: 01-11-2003, 01:08 AM
  5. Word Count
    By simple in forum C Programming
    Replies: 12
    Last Post: 10-04-2002, 10:47 PM