Simple sscanf parsing problem

T

Timo

I haven't been using ANSI-C for string parsing for some time, so even
this simple task is problematic:

I have a string tmp_str, which includes date + time + newline in
format: "25.6.2008 21:49".

I try to parse date from this string to variables tmp1, tmp2, tmp3:

1st attempt:
sscanf(tmp_str, "%d.%d.%d", &tmp1, &tmp2, &tmp3);

All variables get value 0.

2nd attempt
sscanf(tmp_str, "%d %d %d", &tmp1, &tmp2, &tmp3);

tmp3 = 25, others 0.

Any suggestions?
 
B

badc0de4

Timo said:
Any suggestions?

Post a compilable complete code that exhibits the behaviour.

The following program outputs "25 6 2008 21 49".

=========================

#include <stdio.h>

int main(void) {
int tmp1, tmp2, tmp3, tmp4, tmp5;
const char date[] = "25.6.2008 21:49";

sscanf(date, "%d.%d.%d %d:%d", &tmp1, &tmp2, &tmp3, &tmp4, &tmp5);
printf("%d %d %d %d %d\n", tmp1, tmp2, tmp3, tmp4, tmp5);
return 0;
}
 
A

Ali Karaali

I haven't been using ANSI-C for string parsing for some time, so even
this simple task is problematic:

I have a string tmp_str, which includes date + time + newline in
format: "25.6.2008 21:49".

I try to parse date from this string to variables tmp1, tmp2, tmp3:

1st attempt:
sscanf(tmp_str, "%d.%d.%d", &tmp1, &tmp2, &tmp3);

All variables get value 0.

2nd attempt
sscanf(tmp_str, "%d %d %d", &tmp1, &tmp2, &tmp3);

tmp3 = 25, others 0.

Any suggestions?

You can use
sscanf (str, "%d%*c%d%*c%d %d%*c%d", &a, &b, &c, &d, &e);
 
T

Timo

Thanks for your replies. I found that the reason for this problem was
because of variable types:

unsigned short tmp1;
unsigned char tmp2, tmp3;

They should have been int's, or sscanf format parameters should have
been modified.
 
C

CBFalconer

Timo said:
I have a string tmp_str, which includes date + time + newline in
format: "25.6.2008 21:49".

I try to parse date from this string to variables tmp1, tmp2, tmp3:

1st attempt:
sscanf(tmp_str, "%d.%d.%d", &tmp1, &tmp2, &tmp3);

All variables get value 0.

2nd attempt
sscanf(tmp_str, "%d %d %d", &tmp1, &tmp2, &tmp3);

tmp3 = 25, others 0.

Any suggestions?

Never use a scanf function without checking the error return.
 

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

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top