简体   繁体   English

如何在printf中连接数字

[英]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.我是 C 编程新手,不确定如何连接整数。

printf() has special format specifiers that enables you to inject variables into the resulting string. printf()具有特殊的格式说明符,使您能够将变量注入到结果字符串中。 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.我们做 scanf 的原因是因为我们想要用户输入,无论用户在 scan f 中输入什么,都会作为 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我们使用 %s 是因为 index 是一个字符串,对于诸如整数、浮点数和字符之类的东西,您使用 %d、%f 或 %c 否则如果您尝试使用 %d 则它不会编译,如果它实际上是一个字符串

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.在第二个 printf 的末尾,我们使用了我们想要使用的整数的名称,显示将打印的字符串中的值。

The array with the char index[20];具有 char 索引 [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.是假设字符串不会超过 20 位,如果您想要的多于您可以写的长度,那么您希望它有多长,如果您希望它少一些,如果您愿意,可以将其写成 0。 (This would give it eight character input, because a byte can store 8 bits, so 8 characters). (这将给它八个字符输入,因为一个字节可以存储 8 位,所以 8 个字符)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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