How to create a format string used by eg sscanf

D

devrobcom

Anyone knowing a better way of creating a format string than this?

WCHAR sw_arg[100];
int val1, val2;
WCHAR mstring[32];
WCHAR inbuffer1[] = L"-value1 100 -value2 1000 -string1 mystring\t";
int read_no2;

/*
* create format string
* sw_arg = L"-value1 %d -value2 %d -string1 %32s\t%n"
*/
swprintf(sw_arg, L"-value1 %c%c -value2 %c%c -string1 %c%d%c\t%c%c",
'%','d', '%','d',
'%', 32, 's', '%', 'n');

ret = swscanf(inbuffer1, sw_arg, &val1, &val2, mstring, &read_no2);
 
M

mdler

Hello

Why doing so complicated

just use

ret = swscanf(inbuffer1, L"-value1 %d -value2 %d -string1 %32s\t%n",
&val1, &val2, mstring, &read_no2);
 
D

devrobcom

Hi

Currently it looks like your example, but now the lengths have to be
changed. And I have to change in all files in all projects, about 200
places. To make this easyier in the future I just want to use a define
for the length.
 
D

Dave Thompson

Anyone knowing a better way of creating a format string than this?

WCHAR sw_arg[100];
int val1, val2;
WCHAR mstring[32];
WCHAR inbuffer1[] = L"-value1 100 -value2 1000 -string1 mystring\t";
int read_no2;

/*
* create format string
* sw_arg = L"-value1 %d -value2 %d -string1 %32s\t%n"
*/
swprintf(sw_arg, L"-value1 %c%c -value2 %c%c -string1 %c%d%c\t%c%c",
'%','d', '%','d',
'%', 32, 's', '%', 'n');
The standard version of swprintf takes buffer, SIZE, format, values.

You can *printf a % with %%, and a specifier char like any other:
swprintf (sw_arg, sizeof sw_arg / sizeof *sw_arg,
L"-value1 %%d -value2 %%d -string1 %%%ds\t%%n", 32);

FAQ 12.6 at usual places and http://c-faq.com .
ret = swscanf(inbuffer1, sw_arg, &val1, &val2, mstring, &read_no2);

But %32s is wrong for a WCHAR[32], you want %31s.
(The size to fgets snprintf swprintf includes the terminating null
character, but the length to *scanf %s or %[..] does not.)

Also \t in a format string matches _all_ whitespace, not specifically
a tab character. If you wanted the latter use e.g. %*1[\t].

- David.Thompson1 at worldnet.att.net
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top