Peter Dragun wrote:
> I have been reading upon, how dangerous gets() is, could you help me
> provide an alternative using scanf or fgets(without reading a file, but
> still using the stdin)?
/* untested code - beware! */
#include <stdio.h>
#include <string.h>
int chop(char *s)
{
int chopped = 0;
char *p = strchr(s, '\n');
if(p != NULL)
{
*p = '\0';
chopped = 1;
}
return chopped;
}
#define SOME_SIZE_OR_OTHER 32
int main(void)
{
char buf[SOME_SIZE_OR_OTHER] = {0};
if(fgets(buf, sizeof buf, stdin) != NULL)
{
if(chop(buf))
{
printf("The string is [%s]\n", buf);
}
else
{
printf("The string was a tad long. Here's "
"some of it: [%s]\n", buf);
if(fgets(buf, sizeof buf, stdin) != NULL)
{
printf("Here's some more: %s\n", buf);
}
}
}
else
{
printf("EOF or error encountered.\n");
if(ferror(stdin))
{
printf("Error.\n");
}
else
{
printf("EOF.\n");
}
}
return 0;
}
--
Richard Heathfield :
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ:
http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc:
http://users.powernet.co.uk/eton