cstringloopsmultidimensional-arrayfputs

Should I use fputs or putchar?


Here is my following program. I don't want a new line, which is why I used fputs() instead of puts()

char words[5][6] = {"One", "Two", "Three", "Four", "Five"};
for (i = 0; i <= 4; i++)
   fputs(words[i], stdout);

I was wondering if this line of code is safe enough to use as an alternative to this code.

for (i = 0; i < 5; i++)
{
   for (j = 0; j < 6; j++)
   if (words[i][j] != NULL)
      putchar(words[i][j]);
   else
      continue;
}

Note: I'm aware the loop on the second code section needs a little work, particularly on the if statement, but I was wondering about the output overall. I'm asking this question, because on my very first question, I used gets() and was told not to. So I wanted to avoid bad keywords so to speak.


Solution

  • Should I use fputs or putchar?

    I would recommend that you use fputs for your purpose because it achieves your objective without needing to reinvent the wheel.

    Your second approach with putchar will also work but again why to reinvent the wheel? However if you must use putchar for some reasons, you need to replace continue with break to break out of the inner loop on encountering a null character which marks the end of string.