Qbik
Qbik

Reputation: 6157

Reading hour with scanf() - how to disregard part of input

I have following data :
10:15:14 D
00:15:14 T
00:15:14 G

and seven variables :

int h1,h2,m1,m2,s1,s2;
char mark;

output for first line of data should be :
h1==1
h2==0
m1==1
m2==5
s1==1
s2==4
mark=='D'

how to disregard ":" while using scanf() ?

Upvotes: 0

Views: 256

Answers (3)

Pierre Chatelier
Pierre Chatelier

Reputation: 221

You can use a trash variable to scan the ':' part with %c

scanf("%1d%1d%c%1d%1d%c%1d%1d", &h1, &h2, &trash, &m1, &m2, &trash, &s1, &s2);

But, I also vote to not use scanf and use more robust input parsers (depending on the context you are using it in)

Upvotes: 0

Aneri
Aneri

Reputation: 1362

You can do it like

int h1,h2,m1,m2,s1,s2;
h1 = h2 = m1 = m2 = s1 = s2 = 0;
char mark;
if (scanf("%1d%1d:%1d%1d:%1d%1d %c", &h1, &h2, &m1, &m2, &s1, &s2, &mark) != 7)
{
    //some error handling
}

It's indeed strange to use different variables for digits rather than for hours, mins and seconds, like

scanf("%d:%d:%d %c", &h, &m, &s, &mark);

For those commenting that cstdio is obsolete, personally I like it more than iostream.

Upvotes: 3

Michael Wild
Michael Wild

Reputation: 26381

Reading the docs you'll see that it's as simple as

int h, m, s;
char mark;
const char* buf = "00:15:14 D";
sscanf(buf, "%d:%d:%d %c", &h, &m, &s, &mark);
fprintf(stdout, "h = %d, m = %d, s = %d, mark = %c\n", h, m, s, mark);

Upvotes: 1

Related Questions