Thread: How to not read in a quote with sscanf

  1. #1
    Fountain of knowledge.
    Join Date
    May 2006
    Posts
    794

    How to not read in a quote with sscanf

    I was trying to read a quotes string such as
    "His name was "Fred" and his number was 2""
    So I want to read in 'Fred' into a string but not the quotes.

    So I try
    Code:
    sscanf(input_string,"His name was \"%s\" and his number was %d", his_name, &number)
    But that gives an error - well it does not read in a number at all.

    So I change it to
    Code:
    sscanf(input_string,"His name was \"%s and his number was %d", his_name, &number);
    Which works but it gives his name as Fred" ie with an unwanted quote mark at the end of is name. So how do I make it read the name without the trailing quote?

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,794
    %s reads till it encounters space
    %[^\"] should read till it encounters \"

    you should add the width specifier to prevent buffer overrun

    Code:
    char name[25];
     sscanf(input_string,"His name was \"%24[^\"]\" and his number was %d", name, &number);
    Have not tested it - but think it will work
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    David J. Wheeler

  3. #3
    Fountain of knowledge.
    Join Date
    May 2006
    Posts
    794
    Quote Originally Posted by vart View Post
    %s reads till it encounters space
    %[^\"] should read till it encounters \"

    you should add the width specifier to prevent buffer overrun

    Code:
    char name[25];
     sscanf(input_string,"His name was \"%24[^\"]\" and his number was %d", name, &number);
    Have not tested it - but think it will work

    Thanks I expect it will work, I used a similar thing with fscanf to read a line
    ie "%[^\n]\n" but for some reason it never occured to me to use that method with this problem.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to read a file stream entirely into a vector?
    By jiapei100 in forum C++ Programming
    Replies: 4
    Last Post: 01-06-2008, 03:22 PM
  2. read only folder on Windows
    By George2 in forum Windows Programming
    Replies: 2
    Last Post: 11-05-2007, 09:18 AM
  3. I am lost on how to read from file and output to file?
    By vicvic2477 in forum C++ Programming
    Replies: 4
    Last Post: 02-27-2005, 11:52 AM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  5. Read Array pro!!Plz help!!
    By Supra in forum C Programming
    Replies: 2
    Last Post: 03-04-2002, 03:49 PM