Home > Software engineering >  Is it possible to print a string then a variable and string again in one printf?
Is it possible to print a string then a variable and string again in one printf?

Time:09-02

If I have a variable int age = 5, and I want to print "You are 5 years old". Is it possible to do this in ONE printf?

I have programmed little bit in java and I know that it is possible in java with help of a . I was wondering if you could do the same in C?

I think in java it is something like println("You are" age "years old); It was long time ago so I might be wrong.

Thanks!

CodePudding user response:

Yes –

printf("You are %d years old", age);

You can refer to the printf documentation for the rest of the format specifiers; %d is the one generally used for decimal integers.

CodePudding user response:

Another somewhat foolish way:

printf( "%s %d %s\n", "You are", age, "years old" );

The first string ("format specifier") indicates "a string followed by an integer value followed by another string and a newline."

The other stuff is pretty obvious, but each must match the datatype that the format string specifies.

CodePudding user response:

It's all about format specifiers. @AKX provided the answer as you required.

Further more you can check out :

  1. https://www.freecodecamp.org/news/format-specifiers-in-c/
  2. http://www.csc.villanova.edu/~mdamian/C/c-input-output.htm

to know more format specifiers in C.

CodePudding user response:

printf("You are %d years old",age); if you are curious what that %d is check control strings and formatted input/output inc

  • Related