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?
1 Answer
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);
6 Comments
John Zwinck
@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.
user3493439
But I am not using files. I have defined an array and taking input by using the function gets().fgets() is used for files.
DevSolar
@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.Jeegar Patel
@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
DevSolar
It should be noted, however, that
fgets() preserves the newline if it reads one, so you have to handle that yourself. |
NULLat the end, but'\0'.\0is named NUL. By the way,gets()is too dangerous, you should replace it withfgets().gets()apparently does not put a\0at the end of the string, the problem could be somewhere else in your program. The\0could be overwritten by an out of bounds index that occurs after the call togets.A terminating null character is automatically appended after the characters copied to str.So apparently you are doing something else completely wrong.