Solved

Using 'enter' to return

Posted on 2006-07-20
22
362 Views
Last Modified: 2008-03-10
Im not sure how to approach this problem....

For my project, it uses an option based menu.

ie Press 1, enter data, get some stuff back, return to menu.


That's cool, but an 'additional' requirement is to enable the user to return to the main menu, by having no data & pressing 'enter'

ie press 1, press enter, return to menu



So my thoughts so far.

When I scanf in the input, look for an empty string. But what does the scanf string look like when the user input is 'enter' ?


I guess Im looking for any way to check if the user has pressed enter. That way I could send off the input string to a checker method and, if neccessary, return the user to the main menu

Any advice?


0
Comment
Question by:Benjamin_Barrett
  • 8
  • 8
  • 5
  • +1
22 Comments
 
LVL 8

Expert Comment

by:deepu chandran
Comment Utility
Hi,

Your question is not so clear,give some code.Then only i can made clear about your doubt

cheers
deepu
0
 
LVL 45

Accepted Solution

by:
sunnycoder earned 400 total points
Comment Utility
Hi Benjamin_Barrett,

Use fgets to read in the input ... fgets reads in a string along with the trailinh newline ...
Use strtol function to convert this input into required number ...

You can compare this string to "\n"  using strcmp() function

Cheers!
sunnycoder
0
 

Author Comment

by:Benjamin_Barrett
Comment Utility
Ok
Sure,

The main menu looks like this:

      printf("\n\nMain Menu:\n");
      printf("1) ASCII to binary generator\n");
      printf("2) Fractions\n");
      printf("3) Age Calculator\n");
      printf("4) Matching Brackets\n");
      printf("5) Sorting\n");
      printf("6) Logging\n");
      printf("7) Exit\n");
      printf("Select your option: ");

So if the user selects 1, they'll go into the ASCII to binary generator. There they can input a string and get the binary equivalent.


The additional requirement is:

If, instead of inputting a string,  the user just presses enter, they will be returned to the main menu.


So if my scanf is putting the input in to a string, is there any way to check that string to see if the user has just pressed enter?

thanks
0
 

Author Comment

by:Benjamin_Barrett
Comment Utility
Sunnycoder,

So instead of scanf I should use fgets?

that way I can check if the string just contains "\n"   ?

Ta
0
 

Author Comment

by:Benjamin_Barrett
Comment Utility
But with fgets()

doesnt it take a "stream" as an argument? Like a file pointer. What would be the stream in my case?


atm Im using

scanf("%s", toSort);

thanks
0
 
LVL 45

Expert Comment

by:sunnycoder
Comment Utility
Hi Benjamin_Barrett,

stream will be stdin ... By default each C program has 3 streams,
stdin - standard input
stdout - standard output
stderr - stnadard error

These are defined in your stdio.h file

Cheers!
sunnycoder
0
 

Author Comment

by:Benjamin_Barrett
Comment Utility
Ah!! many thanks Sunnycoder

Ive got my lunch now so I'll try it out and get back to you in about 2 hrs

thanks
Benjamin
0
 
LVL 8

Expert Comment

by:deepu chandran
Comment Utility
hi

no need to check '\n' in the strings
you can check '\0' like here

if(name[0]=='\0')   // suppose name is your string gets from the user
i think it will work

cheers
deepu


0
 
LVL 45

Expert Comment

by:sunnycoder
Comment Utility
Hi deepudeepam,

"\0" and "\n\0" are two different unidentical strings.

Cheers!
sunnycoder
0
 
LVL 8

Expert Comment

by:deepu chandran
Comment Utility
hi sunnycoder,

That i know but i tried it in VC++ 6 compaler.I got out put thats why i post it.
here is my code

#include<stdio.h>
#include<conio.h>

void main()
{
      char name[50];
      
      gets(name);
      if(name[0]=='\0')
      {
            printf("Enter");
      }
      else
      {
            printf("\n%s",name);
      }
      getch();
}

i think this will clear it out

cheers
deepu
0
 
LVL 45

Expert Comment

by:sunnycoder
Comment Utility
I am not sure if VC++ 6.0 has conio.h ... that aside gets() is an unreliable input function ... Read its help page in documentation on your system.

The most robust way of accepting input from user in C is to use fgets ... You get to control how much you read, so no memory thrashing possible ...
Next you have all avenues open for performing all kinds of validation checks on the strings and then you can convert it to whatever data type you desire.
0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 8

Expert Comment

by:deepu chandran
Comment Utility
hi,
   <conio.h> is there,

actually i just impliment his problem in a simple way i think.Thank you for ur valuable information.

So i can change like this
fgets(name,50,stdin);
if(name[0],'\n')
{
    printf("Enter");
}
else
{
    printf("\n%s",name);
}

so it is so reliable right
0
 
LVL 45

Expert Comment

by:sunnycoder
Comment Utility
thats my point ... name[0] will be \n and not \0 .. thanks :)
0
 
LVL 7

Expert Comment

by:nafis_devlpr
Comment Utility
why so much fuss

take a look at the following code

char ch[100];
gets(ch);

if(ch[0] == NULL)
      printf("Enter pressed");
else
      printf("ch = %s\n",ch);

so you just have to check whether the first character of the string is NULL(\0) or not, if NULL then only enter was pressed, so you can show the menu again.

or you can do this

char ch[100];
ch[0]=getchar();
if(ch[0] == '\n')
      printf("Enter Pressd");
else
      {
            gets(ch+1);
            printf("ch = %s",ch);
      }

you can any of the above.

Hope this helps

Nafis
0
 

Author Comment

by:Benjamin_Barrett
Comment Utility
ok I really like the idea of fgets, as I can control the number of chars as user inputs.

I changed the code, compiled ok. But...

When I ran it, it went to the menu. I choose '1'.

Immediately the ASCII2BIN generator ran & printed out 00001010. I didnt entyer anything
*then* returned to the main menu.

included the first part of my code below

int main(void)
{
      int optionStats[NUM_OPTION_STATS];
      char lastOutput[STATS_BUF_LEN];

      int check;
      int menuOption[2];

      printf("\n\nMain Menu:\n");
      printf("1) ASCII to binary generator\n");
      printf("2) Fractions\n");
      printf("3) Age Calculator\n");
      printf("4) Matching Brackets\n");
      printf("5) Sorting\n");
      printf("6) Logging\n");
      printf("7) Exit\n");
      printf("Select your option: ");

      scanf("%s", &menuOption);

      char option;
      option = menuOption[0];
      
       //Switching on menu option
      switch(option)
      {

      case '1':
            printf("\nASCII to Binary Generator");
            printf("\n---------------------------\n");
            printf("Enter a string (1-5 characters): ");

            
            char toSort[60];
            int length;

                //Change here
            fgets(toSort,5,stdin);

            if(strcmp(toSort, "\n"))
                  {
                  main();
                  }


            //scanf("%s", toSort);





                //redundant code below
            length = strlen(toSort);
            if (length<=5)
                  {
                  asciiBinary(length, toSort);
                  }
            else
                  {      
                  //if string >5 reject
                  printf("\nInputted string is too long. Please re-enter a string 1-5 characters in length\n");
                  }
                  return EXIT_SUCCESS;

            break;


Many thanks for your help guys, I think I mentioned before that my course is an online uni one....so the ExEx people are like my tutors!

Benjamin

0
 
LVL 45

Expert Comment

by:sunnycoder
Comment Utility
Nafis,

Here is a quote striaght out of gets man page

Never use gets(). 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.

Do I need to say more that you should not be using gets ... Use fgets instead ... If you use fgets, \n is read into the buffer ... that is what the entire fuss is all about ...

HTH
0
 
LVL 45

Expert Comment

by:sunnycoder
Comment Utility
That 1010 is the spare \n left in the input buffer after you have scanf'ed your option ...
scanf ("%s\n", ..) should help ...
I would recommend getting rid of scanf's altogether... fgets is safer, more predictable, cleaner ...
0
 
LVL 8

Assisted Solution

by:deepu chandran
deepu chandran earned 100 total points
Comment Utility
hi,
This is a bad idea to call ur main() function inside ur program body.

if(strcmp(toSort, "\n"))
               {
               main();
               }
also you can change
if(toSort[0]=='\n')  : You can avoid using the strcmp() because it may take some extra execution time.

ok cheers

deepu
0
 

Author Comment

by:Benjamin_Barrett
Comment Utility
Legend!!

cool man, the fgets() way works great.

Point taken about calling main() within main() - its got stack overflow& memory issues written all over it. But I'll ask that as another question.


Once last thing about fgets(), for the 2nd arg should that be the exact length of chars you want to read in? Or should I allow room for control chars?

ie if I want 5 chars from the user is it

fgets(toSort,6,stdin);

Thank you
Benjamin
0
 
LVL 45

Expert Comment

by:sunnycoder
Comment Utility
from the man page

SYNOPSIS
#include <stdio.h>

char *fgets(char *restrict s, int n, FILE *restrict stream);

DESCRIPTION
The fgets() function shall read bytes from stream into the array pointed to by s, until n-1 bytes are read, or a <newline> is read and transferred to s, or an end-of-file condition is encountered.

Assuming that your input is not exhausted, fgets(toSort,6,stdin); would read in 5 bytes of input and place a \0 at the last index
0
 

Author Comment

by:Benjamin_Barrett
Comment Utility
Ah cool. Found a copy of the man pages, will read that first next time.
0
 

Author Comment

by:Benjamin_Barrett
Comment Utility
fyi  justed posted a question on calling main() here....

http://www.experts-exchange.com/Programming/Programming_Languages/C/Q_21925814.html
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now