Link to home
Start Free TrialLog in
Avatar of theravibes
theravibes

asked on

Problem exiting menu on Enter key

I am having a bit of a problem with a project that I am working on...

Here is what I need to be able to do.

The user will be entering data into a set of fields.
If the end user does not enter a value into the field and presses enter,
it will quit the loop.

That is it...

The problem that I have right now is with scanf and gets, if the user presses enter and no value is entered, it will insert a newline character, and remain in the field.

Thanks for your help...
Avatar of Jaime Olivares
Jaime Olivares
Flag of Peru image

you can use gets() to read user entry, it will return anyway, and then use sscanf to apply scanf to the string filled by gets.
sscanf() will return you the number of arguments read, so you will know if input is complete
First of all,usage of gets() is not recommended because of buffer overrun problems.You can use fgets() instead.Read the man pages for gets() for details.

char str[MAX];
You can use scanf("[^\n]",str); or fgets(str,MAX,stdin); to store a line of text(till enter is pressed)

To store everything until enter is pressed into an char array str.Then,you can do the parsing for the values yourself.(You can use sscanf() here to parse the string for values,as jaime pointed out)

ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of theravibes
theravibes

ASKER

Worked like a charm...

Thanks jkr...
Hi Tyson,

Glad to know you solved your problem,but here's why i said gets() should not be used.

From the man pages: (http://www.rt.com/man/getc.3.html)

       Because it is impossible to tell without knowing the  data
       in  advance  how  many  characters  gets()  will read, and
       because gets() will continue to store characters past  the
       end  of  the buffer, it is extremely dangerous to use.  It
       has been used to break  computer  security.   Use  fgets()
       instead.

You can use jkr's idea using fgets() instead of gets()