如何在C中创建格式化的字符数组(字符串)?

时间:2017-01-24 09:16:11

标签: c codeblocks

我想完成像

这样的事情
{    
   char st[30] = "This is number %d", 1;

   printf("%s", sentence);
}

但显然它不起作用......

编辑:修正了标题

2 个答案:

答案 0 :(得分:3)

您将不得不与初始化分开进行格式化。

char st[30];

snprintf(st, sizeof st, "This is number %d", i);
printf("%s\n", st);

这不是“字符串数组”;顺便说一句,它是一个单独的字符串。如果你真的想要做一个数组(如i暗示的那样),你必须将上面的数据放在一个循环中:

char st[20][30];

for(int i = 0; i < 20; ++i)
{
  snprintf(st[i], sizeof st[i], "This is number %d", i);
}

然后你可以打印出来:

for(int i = 0; i < 20; ++i)
{
  printf("%s\n", st[i]);
}

答案 1 :(得分:0)

char st[30];// this is the datatype, array name and size.
//then you have to give values to the array indexes.
st[1]="This is number:"; 
//for numbers use number data types int, float etc..
//e.g.
int number = 10;
//and then print
printf("%c ", st[1]);
printf("%i", number);
相关问题