John Dale
John Dale

Reputation: 61

How to created a formatted array of characters (strings) in C?

I'd like to accomplish something like

{    
   char st[30] = "This is number %d", 1;

   printf("%s", sentence);
}

But obviously it doesn't work...

EDIT: Fixed title

Upvotes: 0

Views: 50

Answers (2)

Mindaugas Kazla
Mindaugas Kazla

Reputation: 3

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);

Upvotes: 0

unwind
unwind

Reputation: 399949

You're going to have to do the formatting separately from the initialization.

char st[30];

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

This is not an "array of strings"; it's a single string by the way. If you really wanted to do an array (as the i implies) you'd have to put the above in a loop:

char st[20][30];

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

Then you can print them:

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

Upvotes: 3

Related Questions