Basic C question about scanf

daniel49

Diamond Member
Jan 8, 2005
4,814
0
71
perhaps you could use 2 vaiables one for first name and one for last? calling scanf twice.


or maybe try using gets()

something like
#include <stdio.h>

char input[81];
main()
{
puts("enter some text, then press enter");
gets(input);
printf("you entered %s" , input);
}



/*try those been quite a while since i played with C*/
 

talyn00

Golden Member
Oct 18, 2003
1,666
0
0
read character by character, until you get to a carriage return or newline. with some sort of while loop.
 

kamper

Diamond Member
Mar 18, 2003
5,513
0
0
Originally posted by: daniel49
perhaps you could use 2 vaiables one for first name and one for last? calling scanf twice.


or maybe try using gets()

something like
#include <stdio.h>

char input[81];
main()
{
puts("enter some text, then press enter");
gets(input);
printf("you entered %s" , input);
}



/*try those been quite a while since i played with C*/
Ewww. Please don't advocate the writing of such code. gets is a hideously unsafe call to be making.

To the op, scanf is nasty for the same reason (dead simple buffer overflow). Since you're just reading a string anyways, may I suggest fgets?
 

statik213

Golden Member
Oct 31, 2004
1,654
0
0
Originally posted by: kamper

Ewww. Please don't advocate the writing of such code. gets is a hideously unsafe call to be making.

To the op, scanf is nasty for the same reason (dead simple buffer overflow). Since you're just reading a string anyways, may I suggest fgets?

isn't gets just a wrapper for fgets (using stdin as the stream)?
 

kamper

Diamond Member
Mar 18, 2003
5,513
0
0
No, gets doesn't have a limit on buffer size. So if you pass in a pointer to a 50 byte piece of memory and the user enters 75, gets will write into unknown territory. fgets takes an int, limiting the number of characters it will get. Anything else is left on the stream for the next read. I suppose gets could call fgets with a number it knows is bigger than anything that could be on the stream, but it doesn't really matter.

The bottom line is that gets = bad.