What is sscanf()
and sprintf()
?
What is sscanf()
and sprintf()
?
I mean in comparison to scanf()
and printf()
which are the most common that people have contact at the beginning of learning?
This s
indicates that the operation will occur in a previously existing buffer , as opposed to the console that is normal in the most common input and output of data.
All scan and printf operations take data from a stream or send it to one. It can be the console, a file, or a string , ie something straight into memory.
All of them use a formatting mechanism to read or output data of various types, adapting as needed following rules established in the API of these functions.
Documentation for scanf()
and sprintf()
along with the rest.
SSCANF
According to the book "The ANSI C Programming Language", by Brian W. Kernighan, the sscanf function, whose declaration is
int sscanf(char *s, const char *format, ...);
is a function equivalent to the scanf function, whose declaration is
int scanf(const char *format, ...);
that is, sscanf does the same as scanf, except that input characters are received from string s (see the sscanf statement above).
Example:
int idade, ano;
char *s = (char *) malloc(100 * sizeof(char));
s = "10 50";
sscanf(s, "%d%d", &idade, &ano);
printf("-> %s\n", s);
printf("-> idade: %d, ano: %d", idade, ano);
In the code above the string s has value "10 50" and I use this string as input in my reading, so the variable age and year receive 10 and 50 respectively.
SPRINTF
According to the book "The ANSI C Programming Language", by Brian W. Kernighan, the sscanf function, whose declaration is
int sprintf(char *s, const char *format, ...);
is a function equivalent to the printf function whose declaration is
int printf(const char *format, ...);
That is, sprintf does the same thing as printf, except that the output is written to string s with the addition of the null character '\ 0' at the end of that string. The string s must be large enough to support the result.
Example:
int idade, ano;
char *s = (char *) malloc(100 * sizeof(char));
char *t = (char *) malloc(100 * sizeof(char));
s = "10 50";
sscanf(s, "%d%d", &idade, &ano);
printf("-> %s\n", s);
sprintf(t, "-> i: %d, a: %d", idade, ano);
printf("-> t: %s\n", t);
Using the same previous example (with some additions at the end), I get the age and year values through sscanf, so I write the string "->:% d, a% d" in my string t, being the first% of the variable age, and the second, the year variable. If I print t, I get "-> i: 10, a: 50".