as is shown at the following code. are those two statement as safe as each other?
Code:char c[20]; scanf( "%19s", c ); fgets( c, sizeof(c), stdin );
as is shown at the following code. are those two statement as safe as each other?
Code:char c[20]; scanf( "%19s", c ); fgets( c, sizeof(c), stdin );
As the are in your code you can consider them the same.
But if you for some reason make c smaller some time you would also have to change the formatstring. If you forget about that => bang.
So I think fgets is a little safer.
Kurt
Both these functions are not totally safe. The return key causes the problem. Scanf() leaves a newline hanging in your input buffer. The hanging newline character is then possibly picked up by the next scanf().
Now fgets() simply attaches it to your input string. When you do some processing later, and for instance compare the string with the trailing newline to a given string in your code, you won't get a match!
I would say fgets() is safer, if you remove the trailing newline! Again here is a sample code that shows you how to do this:
Code:// secure string input, fgets() replaces gets() and scanf() #include <stdio.h> // BUFSIZ usually 512 #include <string.h> int main() { char buf[BUFSIZ] = ""; char *p; printf("Please enter a line of text (max %d characters)\n", sizeof(buf)); if (fgets(buf, sizeof(buf), stdin) != NULL) { // remove trailing \n if ((p = strchr(buf, '\n')) != NULL) *p = '\0'; printf("you entered: %s\n", buf); } getchar(); // wait return 0; }
Ask smart questions - if I would be that smart, I wouldn't need to ask questions.
> Both these functions are not totally safe.
Yes, fgets() is safe when used correctly.
The problem you describe (newline in the buffer) isn't a safety issue, it's a programming issue. If you don't want a newline, then remove it (as you describe). If you simply don't care about the newline then there's nothing else to do.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
You're confusing 'unsafe' with 'potentially confusing semantics'. An unsafe function can blow up in your face, but a function with potentially confusing semantics is perfectly safe when you use it right.Both these functions are not totally safe.
scanf() leaves any whitespace hanging in the input buffer. That's only a problem if you mix scanf() with functions or format specifiers that don't strip leading whitespace, and the code isn't written to handle it. Code that isn't written to handle unexpected whitespace gracefully is usually sloppier than my 2 year old niece eating Spaghetti-Os.Scanf() leaves a newline hanging in your input buffer.
Just because I don't care doesn't mean I don't understand.