This question already has answers here:
printf string, variable length item
(2 answers)
Closed 7 years ago.
I need to
printf(%?d)
Where '?' is some int. How can I do it?
I'm using pure c.
I've tried to work with const char* array. But there was no result.
See the printf man page:
int width = 16;
int value = 42;
printf("%*d\n", width, value);
Output:
42
LIVE DEMO
Related
This question already has answers here:
Function returning address of local variable error in C
(3 answers)
returning a local variable from function in C [duplicate]
(4 answers)
How to access a local variable from a different function using pointers?
(10 answers)
Closed 4 months ago.
I know, there are multiple questions about this on StackOverflow but I couldn't find a fitting solution for my problem.
I want to generate product codes (e.g. 12a, important: numbers and letters) and return them and printf. But when I do it in my main I get no result. When I printf("%s\n", pcode) in my generator function it works, but after return pcode I won't get the result.
char* generate(int num) {
char pcode[3];
... // generating code
printf("%s\n", pcode); // correct output
return pcode;
}
int main(void) {
printf("%s\n", generate(12)); // wrong output
}
This question already has answers here:
Printing leading 0's in C
(11 answers)
Closed 2 years ago.
my question is short, if I have the following 2 lines of code:
int var = 01;
printf("%d", var);
the output is : 1
how do I get 01 rather than 1?
Use left padded format string.
Solution
int var = 1;
printf("%02d", var);
This question already has answers here:
C/C++ unsigned integer overflow
(4 answers)
Closed 4 years ago.
I was trying to get into c programming, but in a question a get stuck, please explain this.
int main()
{
char c = 255;
c=c+10;
printf("%d",c);
return 0;
}
the output it gave is
> 9
kindly explain this to me.
The maximum value of a char is 255.
By adding 10 to that number you get 265.
Because that value is not a suitable value for a char it will do 265 % 256 resulting 9
That's why your result is 9
This question already has answers here:
What does "%.*s" mean in printf?
(4 answers)
Closed 6 years ago.
Why the following program work ? & what is difference b/w %d vs %*d ?
#include<stdio.h>
int main()
{
int n=5;
printf("n=%*d\n", n, n);
return 0;
}
What does width meant here by ?
The first n belongs to the * in %*d, so for your example it is %5d. %5d means to print an integer of width 5. Example: 234 is printed as __234 (2 spaces)
This question already has answers here:
Set variable text column width in printf
(2 answers)
Closed 7 years ago.
I know that I could use printf(%Nd, foo) if N is constant and I know it
But the problem is that N is in variable and calculated in program
I could do it with combining sprintf and printf:
sprintf(formatstr, "%%%dd", N);
printf(formatstr, foo);
But is there any cleaner way?
You can put a * in place of the field width. This means the next parameter will specify the width:
printf("%0*d", size, foo);