1

I want to align a text with the help of a variable using the .* format specifier.

Ideally I wanted a space of 100 length with Some Text Here written and then the | sign. But this doesn't seem to work.

#include <stdio.h>

int main()
{
    int prec = 100; // Assume this value to be calculated somehow and not a constant
    char s[20] = "Some Text Here";
    printf("%.*s", prec, s);
    printf("|");

    return 0;
}

Why is this so?

Thanks in Advance.

8
  • try this printf("%100s", s);, is that what you want? Commented Dec 2, 2020 at 20:00
  • 2
    Your code is almost correct, you just need %*s, not %.*s Commented Dec 2, 2020 at 20:05
  • 2
    Replace %.*s with %*s (right aligned) or %-*s (left aligned) Commented Dec 2, 2020 at 20:05
  • 1
    Just number is "field width", while number after '.' is "precision". These two have different meanings (and can be used together). See man 3 printf for details. Commented Dec 2, 2020 at 20:07
  • 1
    @Developer look at the documentation Commented Dec 2, 2020 at 20:07

1 Answer 1

2

The mistake is, that you try to do a precision like with a float (n decimal places). That won't work with a string. You will need to do %*s, not %.*s

Sign up to request clarification or add additional context in comments.

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.