Reuse format strings

I have a collection of format strings for sscanf, such as

"%02d%*1s%02d%*1s%02d"

to read in certain formatted strings, such as dates, times, etc.

I wonder if there is a way to use them in printf without some changes? The example above would not work - at least I can't think of any ways to use it in printf. Is there a way to reuse them?

Can you provide a better example on how you plan to reuse them in a specific printf statement...

As a general rule, no. The functions sscanf and scanf allow format strings that are called scansets. There are like the one you posted.

IF you wanted reuse for a subset of them(that are usable both ways) you can create a .h include file, example:

/* fmtstr.h */
#ifndef FMTSTR_H_INCLUDED
#define FMTSTR_H_INCLUDED 

char fmt1[]="%-4s";
char fmt2[]="%-5s";

#endif
/* end fmststr.h */

In your code include the fmtstr.h file like this:

#include "fmtstr.h"

When you compile be sure to add the directory that fmtstr.h lives in with a -I option.
This way you can compile almost anywhere you need to on the system as long as the directory & file exists and you can read it.

gcc myfile.c -I /home/migurus/myincludedir -o myfile

There is an array of format strings, the input / output routines make decision which one should be used and passes its decision as an index into that array, this index would be used later to actually use the string in the sscanf/printf

---------- Post updated at 02:20 PM ---------- Previous update was at 02:17 PM ----------

Thanks, that idea looks interesting.

You generally want to use the printf() format string rather than the scanf format string if you want to use the same format string for input and output. Try the following C code as an example:

#include <stdio.h>
char	*dtfmt = "%02d/%02d/%02d %02d:%02d:%02d\n";

int main() {
	int	D, M, Y, h, m, s;
	int	ret;
	char	in[80];

	printf("Enter date & time (MM/DD/YY hh:mm:ss): ");
	while(fgets(in, sizeof(in), stdin) != NULL) {
		ret = sscanf(in, dtfmt, &M, &D, &Y, &h, &m, &s);
		printf("Found Month %d, Day %d, Year %d\n", M, D, Y);
		printf("Found Hour %d, Minute %d, Second %d\n", h, m, s);
		printf(dtfmt, M, D, Y, h, m, s);
		printf("Enter another date & time (CTL-d): ");
	}
	printf("\n");
	return ret;
}

and see what you get if you give it the input:

10/21/14 13:07:33
1/2/14        1:2:5
1 Like