I want to read the name entered by my user using C programmes.
For this I wrote:
char name[20];
printf("Enter name: ");
gets(name);
But using gets
is not good, so what is a better way?
I want to read the name entered by my user using C programmes.
For this I wrote:
char name[20];
printf("Enter name: ");
gets(name);
But using gets
is not good, so what is a better way?
On BSD systems and Android you can also use
fgetln
:Like so:
The
line
is not null terminated and contains\n
(or whatever your platform is using) in the end. It becomes invalid after the next I/O operation on stream. You are allowed to modify the returnedline
buffer.I think the best and safest way to read strings entered by the user is using
getline()
Here's an example how to do this:
On a POSIX system, you probably should use
getline
if it's available.You also can use Chuck Falconer's public domain
ggets
function which provides syntax closer togets
but without the problems. (Chuck Falconer's website is no longer available, although archive.org has a copy, and I've made my own page for ggets.)You can use scanf function to read string
i don't know about other better options to receive string,
You should never use
gets
(orscanf
with an unbounded string size) since that opens you up to buffer overflows. Use thefgets
with astdin
handle since it allows you to limit the data that will be placed in your buffer.Here's a little snippet I use for line input from the user:
This allows me to set the maximum size, will detect if too much data is entered on the line, and will flush the rest of the line as well so it doesn't affect the next input operation.
You can test it with something like:
I found an easy and nice solution:
it's based on fgets but free from '\n' and stdin extra characters (to replace fflush(stdin) that doesn't works on all OS, useful if you have to acquire strings after this).