Use width specifier in another specifier


Use width specifier in another specifier



I'm newbie in C.
My question is how could i use value (representing the width specifier) in specifier.


int width_specifier = 1;
char* star = "*";

for (width_specifier;width_specifier<10;width_specifier++)
{
for (int j = 1;j<= width_specifier;j++)
{
printf("%width_specifier.s",star);//Problem is here
}
printf("n");

}





What is the output you're trying to generate? Should the width come from width_specifier or j?
– Barmar
Jun 29 at 22:01


width_specifier


j





I was just trying to do that star exercise without 2 loop.Only 1 loop.
– Wasp Nesser
Jun 29 at 22:58




4 Answers
4



The width specifier is used to control the minimum number of bytes to be written. With "%s", the output is padded with ' '.


"%s"


' '


int main(void) {
for (int width_specifier = 1; width_specifier < 10; width_specifier++) {
printf("%*sn", width_specifier, "*");
}
}



Ouptut


*
*
*
*
*
*
*
*
*



To print various amount of * per line without an inner loop, code can pass a precision to limit the maximum number of bytes to be written with ".*s".


*


".*s"


int main(void) {
for (int width_specifier = 1; width_specifier < 10; width_specifier++) {
int precision = width_specifier;
printf("%.*sn", precision, "**********");
}
}



Output


*
**
***
****
*****
******
*******
********
*********



If you read e.g. this printf (and family) reference you will see that it is (kind of funny thinking about what you want to print)... The star.


printf



That means an int argument will be read for the field width.


int



As in


printf("%*sn", j, star);



As in the documentation you can always have the width itself a specifier:


printf("%*s", j, star);



Where that's taking j as the width argument, star as the value to be formatted.


j


star





Shouldn't j be width_specifier?
– Barmar
Jun 29 at 21:59


j


width_specifier





If it's trying to create a diagonal line, then no. If it's a vertical line then yes.
– tadman
Jun 29 at 22:00


printf("width_specifier = %c",star);



And other formatting: https://www.tutorialspoint.com/c_standard_library/c_function_printf.htm





The argument corresponding to %c must be a char, but star is char*.
– Barmar
Jun 29 at 22:01


%c


char


star


char*






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Export result set on Dbeaver to CSV

Opening a url is failing in Swift