Pritam Karmakar
Pritam Karmakar

Reputation: 183

How to achieve this delimiter in C?

Suppose I will enter the data in this way.

18-MAR-1995

Now I want to store this one data into different variables using one single scanf() function.

Let say the variables are,

int dd,yy;
char month[3];
  1. 18 will store in dd variable
  2. MAR will store in month variable
  3. 1995 will store in yy variable

I tried this one

scanf("%d[^-]%s[^-]%d",&dd,s,&yy);

IDEONE LINK HERE

Upvotes: 1

Views: 131

Answers (3)

Ajay Brahmakshatriya
Ajay Brahmakshatriya

Reputation: 9203

The issue with your code is that you used [^-] which means stop when you see [^-] literally. You want to only match -. So that is wrong. Try this one

scanf("%d-%[^-]-%d", &d, m, &y);

Here you stop the parsing of %d when - is found and the string stops when next - is found. Final integer goes into y.

Also as mentioned by StoryTeller you need 4 characters for storing "MAR" if you want to treat it as a string.

Here is a demo

Upvotes: 3

Michaël Roy
Michaël Roy

Reputation: 6481

try this:

// for format dd-mmm-yyyy format ex. 18-MAR-1995

int dd,yy;
char month[4];   // note the extra char for null char at end.

char* sz = "18-MAR-1995";
if (sscanf(sz, "%d-%3s-%4d", &dd, month, &yy) != 3)
{
   // sz is not in expected format
}

Upvotes: 1

Thomas
Thomas

Reputation: 182000

Note that scanf syntax is different from regular expressions; it seems you're confusing the two. Non-special characters match themselves, so - needs no special treatment. Furthermore, %s always expects a whitespace-terminated string (word), so you need %3c to match three characters exactly.

So the correct format string is:

scanf("%d-%3c-%d", &dd, month, &yy);

Note that no terminating '\0' byte will be added to month! So this is well-defined behaviour, but don't try to use month as a null-terminated string.

Upvotes: 6

Related Questions