-
scanf or gets?
I have been reading through a ton of tutorials trying to learn C programming. I have read in some places that scanf is bad and shouldn't be used if possible and other places that gets is worse than scanf. Which should I be using and if it depends when shoulld I use which?
~Sven
-
Use neither. fgets() is the best. See the FAQ.
Why gets() is bad: http://faq.cprogramming.com/cgi-bin/...&id=1043284351
Why fgets() is good: http://faq.cprogramming.com/cgi-bin/...&id=1043284385
scanf("%s", s) is bad because it stops at spaces, among other things.
-
What do I put where the file pointer goes in fgets then?
~Sven
-
Code:
#include <string.h> /* for strchr */
char s[SOME_SIZE], *p;
fgets(s, sizeof(s), stdin);
/* or sizeof s, or SOME_SIZE */
/* now you have a line, but it's newline terminated */
if((p = strchr(s, '\n'))) *p = 0;
/* now you have what you want */
printf("Hello, %s!\n", s);
I often use BUFSIZ for SOMESIZE. It's at least 512 and defined in <stdio.h>.
-
Read my second FAQ link (you might have caught my post before I edited it). This is the sample program provided:
Code:
#include <stdio.h>
#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)
{
printf ("Thank you, you entered >%s<\n", buf);
/*
* Now test for, and remove that newline character
*/
if ((p = strchr(buf, '\n')) != NULL)
*p = '\0';
printf ("And now it's >%s<\n", buf);
}
return 0;
}
/*
Program output:
Please enter a line of text, max 512 characters
this is a test
Thank you, you entered >this is a test
<
And now it's >this is a test<
*/
-
You should read
this
Prelude is cerainly master of the universe, too bad she's not with us anymore...
-