0

I am talking input using gets() function. So, I want to check where string ends. But NULL is not inserted at the end of the string as it is inserted by using scanf(). So how can I do this?

5
  • 4
    It's not NULL at the end, but '\0'. Commented Apr 8, 2014 at 12:36
  • 2
    And \0 is named NUL. By the way, gets() is too dangerous, you should replace it with fgets(). Commented Apr 8, 2014 at 12:38
  • 2
    gets() itself insert null character. Commented Apr 8, 2014 at 12:39
  • If gets() apparently does not put a \0 at the end of the string, the problem could be somewhere else in your program. The \0 could be overwritten by an out of bounds index that occurs after the call to gets. Commented Apr 8, 2014 at 12:43
  • read documentation before asking question. It clearly says: A terminating null character is automatically appended after the characters copied to str. So apparently you are doing something else completely wrong. Commented Apr 8, 2014 at 12:43

1 Answer 1

8

gets() absolutely does insert a null terminator. However, please note that gets() is deprecated and should not be used at all. Use fgets() instead, as it avoids buffer overrun vulnerabilities.

To use fgets on standard input:

char buffer[256]
fgets(buffer, sizeof(buffer), stdin);
Sign up to request clarification or add additional context in comments.

6 Comments

@Mr.32: yes, '\0' is an ASCII NUL terminator, and "\0" is a string containing a NUL followed by an implicit second NUL because all C strings have one added on automatically.
But I am not using files. I have defined an array and taking input by using the function gets().fgets() is used for files.
@user3493439: There is no way to use gets() safely, while there is a way to use fgets() with stdin as the third parameter. Really, gets() is so toxic that GCC emits a warning even without warnings enabled, and it has been officially deprecated from the language standard. Do not use gets(), ever.
@user3493439 if you are not using files and giving input by command line still yet gets() will remove your last \n and insert null terminator in string
It should be noted, however, that fgets() preserves the newline if it reads one, so you have to handle that yourself.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.