简体   繁体   中英

How can I combine these two printf statements in C?

I'm trying to print "Hello the number 5 is correct!" in C.

The way I'm doing it now is with two printf statements:

printf("Hello the number %d", number);
printf(" is correct!\n");

How can I do this in one statement like in Java:

System.out.println("Hello the number "+number+" is correct!");

I've tried doing it this way in C:

printf("Hello the number %d", number, " is correct!");

but the "is correct!" doesn't show up.

is there a way to do this in one statement? I'm sorry I'm very new to C.

You can embed the format specifier into the middle of the string like so:

printf("Hello the number %d is correct!\n", number);

Alternatively, you can use another format specifier for the rest of the string:

printf("Hello the number %d%s\n", number, " is correct!");

The printf function expects the format of your string, followed by the arguments referenced by the format.

printf("Hello the number %d is correct!\n", number);

In your case printf("Hello the number %d", number, " is correct!") will be understood as " Hello the number %d " as the format of your string with number and " is correct! " as arguments and as you have only one argument referenced in your format, " is correct! " doesn't appear in the resulting string, this is the reason why " is correct! " doesn't show up.

Your try is not working because you have 1 appender (%d) but 2 parameters ( number and " is correct!" )

try instead...

int main(void) {
     int number =0;
   printf("Hello the number %d   is correct!", number);
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM