1

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

2
  • 1
    You cannot store string in char, which can contain only one character (typically one byte). Commented Feb 26, 2016 at 4:21
  • 1
    Simply : String is an array of characters. Commented Feb 26, 2016 at 4:22

3 Answers 3

1

You should allocate enough buffer and use sprintf().

int a=01; /* this is octal value */
int b=10;
int c=2012;

char date[40]; /* 32-bit long integer will be at most 11 digits including sign in decimal */
sprintf(date, "%d/%d/%d", a, b, c);
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

You should add #include <stdio.h> to the top of your code to use printf() and sprintf().
@MikeCAT Thanks, I had that in my code but missed it when I copied/pasted. I added it.
0

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 the sprintf () function is used to create strings as output using formatted data. The syntax of the sprintf () function is as follows:

int sprintf (char *string, const char *form, … );

You can also use itoa, but it is not standard.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.