Thread: How do I read in this as a string?

  1. #1
    Registered User
    Join Date
    Sep 2008

    How do I read in this as a string?

    I have a file that I can already read in

    If the file says:

    Jamie 20

    I use this code:
    fscanf(file,"%s %lf", struct_ptr[1].name, &struct_ptr[1].number);

    struct_ptr[1].name = "Jamie" and then struct_ptr[1].number = 20

    so... what if I had:

    Jamie Lynn 20

    I dont know how to make struct_ptr[1].name equal the whole string "Jamie Lynn"

  2. #2
    Registered User
    Join Date
    Jan 2008
    You can try this where 20 in %20 is the length of string you need to read.
    But this isn't safe so you should probably try an another method.

    fscanf(file,"%20s %lf", struct_ptr[1].name, &struct_ptr[1].number);

  3. #3
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    That's still going to stop at spaces. There are scansets, so you could do something like %<some number>[^0123456789] to read in up to a digit. (The <some number> is the size of the buffer .name.) Granted, you'll get the space at the end, but that's easily fixable.

  4. #4
    Registered User
    Join Date
    Sep 2008
    no thats not the only name in the file

    I have like:
    Jamie lynn 20
    Eric D. Mcdaniel 40
    Joe 23

    so I need to read in the name for the name part of the struct, then the number for the number part of the struct.

  5. #5
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Rishon LeZion, Israel
    read whole line into temp buffer using fgets
    use strrchr to find last space
    copy the part before space into name
    convert part after space using strtol into number

  6. #6
    Kernel hacker
    Join Date
    Jul 2007
    Farncombe, Surrey, England
    What vart suggests will certainly work. Another method would be to change the input file format so that you have:
    "Joe", 20
    "Jimmy Hoffa", 21
    "E.W. Bloggs", 23
    "Eric John Jones-Smithe", 46
    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. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  2. Message class ** Need help befor 12am tonight**
    By TransformedBG in forum C++ Programming
    Replies: 1
    Last Post: 11-29-2006, 11:03 PM
  3. Replies: 1
    Last Post: 05-30-2003, 02:31 AM
  4. string handling
    By lessrain in forum C Programming
    Replies: 3
    Last Post: 04-24-2002, 07:36 PM
  5. read records fron file into a binary tree
    By Kirsten in forum C Programming
    Replies: 1
    Last Post: 04-23-2002, 02:48 PM

Tags for this Thread