BArtWell
BArtWell

Reputation: 4054

How to parse string with sscanf_s()?

I have the string (45 bytes):

        String1        String2000000000001234

I need get three variable from this string:

char * var1="String1";
char * var2="String2";
int var3=1234;

Here 3 part with fixed length (15 bytes). I need save all parts to variable without spaces for strings and without leading zero for integers.

Is this possible with scanf()? How I can to do that?

Upvotes: 3

Views: 6273

Answers (3)

Chris Dodd
Chris Dodd

Reputation: 126546

The easiest would probably be:

char var1_buffer[31] = "", var2_buffer[31] = "";
sscanf(string+30, "%d", &var3);
string[30] = '\0';
sscanf(string, "%s%s", var1_buffer, var2_buffer);
var1 = strdup(var1_buffer);
var2 = strdup(var2_buffer);

which requires being able to write to the input string. If that's not possible, you could replace lines 3 and 4 with:

int p1 = 0;
sscanf(string, "%30s %n%30s", var1_buffer, &p1, var2_buffer);
if (p1 > 30)
    p1 = 30;
var2_buffer[30-p1] = '\0';

In either case, you should probably add checks of the return value of sscanf to make sure the input string is well-formed.

Upvotes: 0

Sergey
Sergey

Reputation: 8248

According to this, your problem should be solved by the following format:

%*[^a-zA-Z]%s%*[^a-zA-Z]%[^0]s%*[^1-9]%d

Description:

%*[^a-zA-Z] - skip(do not store) until alphabetical, i.e. skip leading spaces

%s - read first string until spaces

%*[^a-zA-Z] - skip trailing spaces until the next string

%[^0]s - read string util zeros

%*[^1-9] -skip until nonzero digits

%d - finally, read the number

Upvotes: 3

mark
mark

Reputation: 5469

Not possible with sscanf. First, you need to pass a char array (and size if you use the _s variety) and not just a char pointer (i.e. it needs to have memory associated with it). Second, strings in sscanf terminate by whitespace, and you have none between String2 and 0000. Write a custom parser for this format.

Upvotes: 4

Related Questions