1

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.

Stargateur
  • 24,473
  • 8
  • 65
  • 91

4 Answers4

1

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.

VHS
  • 9,534
  • 3
  • 19
  • 43
0

gets is inherently unsafe (and was in turn removed from C standard in 2011), fputs is not. I see nothing wrong with your code that uses fputs.

lukeg
  • 4,189
  • 3
  • 19
  • 40
0

fputs is safe to use. gets is, as you said, no good.

Travis
  • 427
  • 4
  • 8
0

puts and fputs are both safe in that context. Your alternative is just a (bad) C translation of fputs. It is wrong because you continue the loop after a null character. If for any reason, garbage (from a previous longer string) exists after first null, you would use it.

And anyway, functions from the standard library might by optimized, so you should use them when possible.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252