0

So i really want this to happen. I have an integer variable and i want to use that variable to give spacing in my printf function but C doesn't give me permission to do that , is there any way around it.

#include<stdio.h>
int main(void){
   int s = 5;
   printf("%sd",s);
}

Thanks a lot in advance!

FIcti_0n
  • 83
  • 3

3 Answers3

7

The * in a format specifier means "I'll pass this number as an argument."

int s = 5;
printf("--%*d", s, s);

output

--    5

Nice page with details here https://www.tutorialspoint.com/c_standard_library/c_function_printf.htm

Stephen Docy
  • 4,738
  • 7
  • 18
  • 31
5

Using * for the width will cause printf to take the width from the next argument, which should have type int:

printf("%*d", s, ValueToBePrinted);

You can find information about printf and other C features in the C standard. In the C 2011 version, formatted I/O is covered in clause 7.21, about <stdio.h>. 7.21.6.1 discusses fprintf, which uses the same format syntax as printf and is referred to from the printf clause, 7.21.6.3. Paragraph 5 discusses using * for a field width.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
0

What do you mean by spacing here ? You can simply put ‘\t’ before ‘%d’ to give a tab before printing the value of the variable. Also ‘%sd’ doesn’t mean anything. Here %d is replaced by the value of your variable stated after the comma, ie, in your case it’s variable s.

  • 1
    You should read the Question, the other Answers too and more over, after you are done reading, then you should read Printf’s manual. After that you should edit or delete your Answer. – Michi Feb 23 '18 at 18:34