2

So basically I'm learning C and they taught us to use the gets() function, which I found that it was removed and cannot be used anymore. So I'm trying to learn to use the alternative, the gets_s() function, but I can't seem to. For example the following code gives me "Undefined reference to gets_s" when attempting to compile.:

char line[21];
gets_s( line, 20 );
printf( "The line entered was: %s\n", line );

A lot of people have said to use fgets() instead of gets() but I don't understand how that will work, since I want to read the user's input, not from a file.

toblerone_country
  • 577
  • 14
  • 26
Osama Qarem
  • 1,359
  • 2
  • 13
  • 15
  • You need to include a header than defines `gets_s`. – Cole Tobin Aug 31 '14 at 15:55
  • 2
    `gets_s` is only available in MSVC. Use `fgets`. – Fred Foo Aug 31 '14 at 16:02
  • 1
    Even better, use `getline` if your system has it (like in recent Posix spec). It is dynamically allocating the buffer for the line, so can accept very large lines (if system resources permit them). – Basile Starynkevitch Aug 31 '14 at 16:04
  • @ user Thanks. fgets wonderfully now. @ Basile I'm still really a newb at programming and all so I dont really understand what buffer is, but I will be looking up getline. – Osama Qarem Aug 31 '14 at 16:08

1 Answers1

6

The function gets_s is not a first-class standard function. It is implemented by Visual Studio (mentioned on MSDN) where it is available if you include stdio.h.

Interestingly C11 introduces it as a somewhat standard function by mentioning it in Appendix K, "Bounds-Checking interfaces" along with other _s functions. However many compilers have chosen not to implement this interface so it is probably best not to rely on it.

To reiterate what user3121023 said, fgets is probably the safest way to go (but you should use sizeof if you can):

fgets(line, sizeof line, stdin);

Note you don't need to pass the one less than the size of the array.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • If you're converting code from MSVC to standardized C, you can use `#DEFINE gets_s(x, len) fgets((x), (len) + 1, stdin)` in the meantime while you update all references, but I'd recommend against it. A simple `sed` command would be better. – Cole Tobin Aug 31 '14 at 17:04