Reputation: 19
#include <stdio.h>
int main() {
char str[50];
printf("Enter a string : ");
gets(str);
printf("You entered: %s", str);
return (0);
}
In my code, why isn't the gets()
function declared? It shows me a bunch of errors such as:
In function ‘int main()’:
error: ‘gets’ was not declared in this scope
gets(str);
^~~~
[Finished in 0.2s with exit code 1]
I want to know why this kind of problem occurs?
Upvotes: 1
Views: 2172
Reputation: 71
I didn't know gets was deprecated, but you can use fgets. https://en.cppreference.com/w/c/io/fgets
Where you have to specify the maximum size available in the buffer (which protects against buffer overflow).
fgets(buffer, sizeOfBuffer, stdin)
Be aware
That fgets also reads the newline character into the buffer while gets doesn't (as mentioned in the comments). So you have to remove the newline character afterwards if you are not interested in it.
Upvotes: 3
Reputation: 144780
gets()
has been removed from the C language. This function cannot be used safely because the size of the destination array is not provided, hence a long enough input line will cause undefined behavior as gets()
will write beyond the end of the array.
Here is a replacement function that takes an extra argument:
#include <stdio.h>
// read a line from stdin, ignore bytes beyond size-1, strip the newline.
char *safe_gets(char *dest, size_t size) {
int c;
size_t i = 0;
while ((c = getc(stdin)) != EOF && c != '\n') {
if (i + 1 < size)
dest[i++] = c;
}
if (size > 0)
dest[i] = '\0';
return (i == 0 && c == EOF) ? NULL : dest;
}
Upvotes: 1
Reputation: 215287
gets
has not been part of the C language for the past 9 years, and prior to that, was deprecated and extremely unsafe - not just difficult to use in a safe/correct manner, impossible. Whoever taught you C is not fit to be teaching.
Upvotes: 9
Reputation: 926
I am assuming you are wanting to get keyboard input from the user?
If you are using c++ you can use cin >> str
If you are using c you will want scanf("%s", &str)
gets
was deprecated in C++11 and removed from C++14
Upvotes: 2