简体   繁体   中英

How to concatenate number in printf

I would to do something like this:

    int index=1;
    for(index=1; index<10; index++)
        printf("Welcome player"+index+". How are you today?");

I'm new in C programming and not sure how to concatenate an integer.

printf() has special format specifiers that enables you to inject variables into the resulting string. In your case you would want to do it like this:

printf("Welcome player %d. How are you today?", index);

See more info here .

what I think you are trying to do is this

   char index[20];
      printf("Enter Name: ");
      scanf("%s", index);
      printf("Welcome player %s How are you today?", index);

The reason we do the scanf is because we want user input, whatever the user will put in the scan f will come out as the output for your printf.

We use %s because index is a string, for things such as ints, floats, and chars you use %d, %f, or %c or else it wouldn't compile if you were trying to use %d if it was actually a string

at the end of the second printf we used the name of the integer we wanted to use, show the value within the string would print.

The array with the char index[20]; is to assume that the string will not be longer than twenty bits, if you wanted more than you can write however long you wish it to be, if you want it less you can write it to be small as 0 if you wished. (This would give it eight character input, because a byte can store 8 bits, so 8 characters).

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