0

I'm trying to learn C for a class next semester, and have a background in python. I would like to print multiple arguments, both strings and various datatype objects using printf(). My code is as follows:

#include <stdlib.h>
#include <stdio.h>

int main(void)
{
    short int x = 1;
    unsigned short int y = 2;

    printf("Short int x: %", x);
    printf("Unsigned short int y: %", y);
}

I am using Eclipse with a CDT plugin, no issues with binaries or anything.

I looked up the man page for printf() but was having some issues with the %. notation. Could someone elaborate on printf's capabilities.

Thank you.

3
  • Use printf("Short int x: %hd", x); and printf("Unsigned short int y: %hu", y); Commented Dec 11, 2014 at 21:00
  • "printf format string" in google search line is a much faster way of finding a comprehensive answer as a first result. codingunit.com/… Commented Dec 11, 2014 at 21:01
  • C "printf" uses a "format string", where each item to be printed has a "%" "format specifier". Here is a good list of format specifiers: cplusplus.com/reference/cstdio/printf Commented Dec 11, 2014 at 21:03

3 Answers 3

3

Unlike Python, the % operator is used only as a format specifier, not as the separation between the string and the arguments.

#include <stdlib.h>
#include <stdio.h>

int main(void)
{
    short int x = 1;
    unsigned short int y = 2;

    printf("Short int x: %d ", x);
}
Sign up to request clarification or add additional context in comments.

2 Comments

So everything is kept w/in the quotations and based on the variable/character type you append a character after the '%' ?
@CyberOps17, That is correct. The arguments are always passed as normal function arguments, separated by a comma.
1

Using the C standard library:

#include <cstdio>

int main() {
    short int x = 1;
    unsigned short int y = 2;

    std::printf("Short int: %hi \n Unsigned short int: %hu \n", x, y);
    return 0;
}

The format string must correspond to the variable type, and also indicates how it should be formatted. %hi is for short int, %i for int, %u for unsigned int... See here.

Comments

0

The % symbol is used in the string as a place holder for where you would like to output the contents of your variable. The % symbol can be followed by different flags or specifiers to help format the output to your needs. Your printf line should look like this:

printf("Short int x: %d", x);

%d or %i indicates that the format of the variable "x" is a number. Here are some references for the printf() function:

http://www.tutorialspoint.com/c_standard_library/c_function_printf.htm http://www.cplusplus.com/reference/cstdio/printf/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.