I'm very new to C. I want to construct a string using 3 integers and "/".
Eg.
int a=01;
int b=10;
int c=2012;
char date = "a/b/c";
Can you please help and let me know what is the correct way to do this.
Thanks in advance
Try this:
#include <stdio.h>
int main()
{
int a=1;
int b=10;
int c=2012;
char date[11];
sprintf(date, "%d/%d/%d", a, b, c);
printf("%s\n", date);
sprintf(date, "%02d/%02d/%04d", a, b, c);
printf("%s\n", date);
return 0;
}
This prints the date in two formats. The second zero-pads while the first does not. Here's the output:
1/10/2012
01/10/2012
#include <stdio.h> to the top of your code to use printf() and sprintf().Use sprintf, which will write to a string, as the name suggests: string print function:
sprintf(date, "%d/%d/%d", a, b, c);
and include the header stdio.h.
Also, doing
char date;
makes date a character, but you want it to be a string. So allocate memory in it:
char date [10];
which makes it a string or an array of characters with 10 elements. But you will be able to store only 9 characters in it, as you have to keep one element for the null-terminator or \0.
How does sprintf work?
If you're confused what sprintf is doing, basically the first argument is where sprintf is printing, the second argument is what to print, and the third, fourth, etc.. arguments are variables which will be substituted by a %d, %s, etc.
For a better explanation, see this:
The C library function
sprintf ()is used to store formatted data as a string. You can also say thesprintf ()function is used to create strings as output using formatted data. The syntax of thesprintf ()function is as follows:int sprintf (char *string, const char *form, … );
You can also use itoa, but it is not standard.
char, which can contain only one character (typically one byte).arrayofcharacters.