user11745417
user11745417

Reputation:

C - how to use sscanf with a formatted string?

I have a string which I have successfully formatted like this (Yes, the whitespaces are inconsistent):

|Prague| |Sunny|
|Prague| |Cloudy|
|Prague| |Rain|
|New York||Sunny|
|New York||No data|
|New York||Rain|

I can change the character | easily to any other char btw.

I want to assign each text this way:

char city; => Prague

char weather; => Sunny

etc.

I tried using sscanf like this: sscanf(input, "|%s||%s|", city, weather); but it doesn't work.

Any ideas what I'm doing wrong? Maybe some regex would help?

The wrong result I'm getting is this by the way:

Prague, ����
Prague, ����
Prague, ����
....

Upvotes: 0

Views: 625

Answers (2)

vmp
vmp

Reputation: 2420

That is because there is a space between the 2 |'s.

You can ignore any characters between the first ending | and the second starting | by adding the %*[^|] which means: "Ignore everything until you find a |.

sscanf(input, "|%s|%*[^|]|%s|", city, weather);

But if you could have two or more words you should use a different specifier than %s:

sscanf(input, "|%[^|]|%*[^|]|%[^|]|", city, weather);

Upvotes: 0

questioner
questioner

Reputation: 188

Try using

char *

instead of

char

char

is only a single character, but you'll need a pointer.

Upvotes: 0

Related Questions