Fetching blanks in strings with sscanf 
Author Message
 Fetching blanks in strings with sscanf

How can I fetch blanks in strings with sscanf? I would like to parse the
following string:

char string [] = "   1   2   3   4";

with sscanf to get  a = "   1"; b = "   2"; c = "   3"; d = "   4";

but sscanf( string, "%4s%4s%4s%4s", a, b, c, d );

gives me a = "1"; b = "2"; c = "3"; d = "4";

--
Luc Le Blanc



Fri, 22 Apr 2005 20:43:22 GMT  
 Fetching blanks in strings with sscanf

Quote:
> How can I fetch blanks in strings with sscanf? I would like to parse the
> following string:

> char string [] = "   1   2   3   4";

> with sscanf to get  a = "   1"; b = "   2"; c = "   3"; d = "   4";

> but sscanf( string, "%4s%4s%4s%4s", a, b, c, d );

> gives me a = "1"; b = "2"; c = "3"; d = "4";

That is because scanfs %s has a different understanding of string than
other functions in the standard library. %s tells scanf to first
discard all whitspace and than read everything until the next
whitespace occures. So you got what you asked for. If you really
need to use sscanf for this (it probably isn't the best choice)
than you'll have to be sure about the total width of the scanned
fields. If you know for sure that all "strings" will be 4
characters long and you know the number of fields to read, than
you can copy all these with a single sscanf:

  sscanf("%4[^\n]%4[^\n]%4[^\n]%4[^\n]", a, b, c, d);

OTOH, if you're unsure about the number of elements that will be
read (that is usually the case, when you need to parse some user
entered text or edited files) than you probably should use
strcpy() in loop rather that sscanf(). Now if the length of the
fields varies it gets even harder.
Can you clarify the requirements?
--

"LISP  is worth learning for  the profound enlightenment  experience
you will have when you finally get it; that experience will make you
a better programmer for the rest of your days."   -- Eric S. Raymond



Fri, 22 Apr 2005 21:07:07 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. How to use fscanf/sscanf when data may be missing (blank)

2. Replace multiple blanks with a single blank

3. Reading a String that contains blanks

4. Blank string

5. Search string where sub_string has trailing blanks

6. Compare string and skip trailing blanks

7. parsing string w/ sscanf() question

8. Using fgets and sscanf Line into Strings

9. reading ints from a string with sscanf

10. HELP! Problems string->float using ATOF,SSCANF

11. sscanf to conv int 2 string

12. web page fetching and cookies

 

 
Powered by phpBB® Forum Software