1

I'm making a menu that lists options 1-3. The user is expected to enter an integer.

scanf("%d", &select_option)

How do I prompt error when user enters a char (for example "a", or "asd" for long strings, or a mixture like "1a2") instead of an expected int? Thanks.

Note: When the user enters a 'char' like 'a', 'asd', the code goes into an infinite loop for some reason.

Here's my program (minimal example):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

        int main(void)
            {
                printf("Favourite sports? \n");
                printf("1. Tennis\n");
                printf("2. Badminton\n");
                printf("3. Basketball\n");
                printf("4. Exit program.\n");
                printf("Enter your choice (1-4): "); 
                scanf("%d", &select_option);

                while(select_option != 4) 
                {
                    switch(select_option)
                    {
                        case 1:
                            printf("You like tennis! Nice! \n");
                            break; 

                        case 2:
                            printf("You like badminton! Nice!");
                            break;      

                        case 3: 
                            printf("You like basketball! Nice!");
                            break; 

                        default:
                            system("clear");
                            printf("Invalid option. Please re-enter your choice (1-4).\n");

                    }//end switch

                printf("Favourite sports? \n");
                printf("1. Tennis\n");
                printf("2. Badminton\n");
                printf("3. Basketball\n");
                printf("4. Exit program.\n");
                printf("Enter your choice (1-4): "); 
                scanf("%d", &select_option);

                }//end while
            }//end main
gsamaras
  • 71,951
  • 46
  • 188
  • 305
WCKennedays
  • 129
  • 1
  • 3
  • 11
  • You might be interested in my [beginners' guide away from scanf()](http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html) to learn more about all the possible pitfalls with `scanf()` and some guidance what else to use. –  Jun 28 '17 at 09:40
  • 1
    get a whole line with `getline`, strip newline character, convert to integer with `strtol`, check if ok – Federico klez Culloca Jun 28 '17 at 09:41
  • If user enters other than numbers just throw an error. For instance `if (select_option < '0' && select_option > '9') { printf("error: wrong input\n"); }` would be as simple as possible. – LinuxStuff Jun 28 '17 at 11:31
  • @LinuxStuff But when the user enters a 'char' like 'a', 'asd', the code goes into an infinite loop for some reason. – WCKennedays Jun 28 '17 at 13:01
  • Try this snippet of code. `if ((select_option > 0) && (select_option <= 9)) { printf("you have entered %d\n", select_option); } else { printf("you have entered wrong menu option\n"); }` This is the simplest way of handling the input. – LinuxStuff Jun 28 '17 at 16:17

2 Answers2

1

You could do this:

#include <stdio.h>

int main(void) {
    int v;
    int ret = scanf("%d", &v);
    if(ret == 1)
        printf("OK, %d\n", v);
    else
        printf("Something went wrong!\n");
    return 0;
}

where I took advantage of the return value of scanf(), and based on that value, I made an assumption. This will fail for the case of "1a2", but will succeed for "12" and "a".

However, this is a broad question and personally the way I would go for it is:

  1. Use fgets() to read input.
  2. Discard newline.
  3. Convert string to integer (with strtol() for example).
  4. Validate input.
gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • I see, thank you. I've seen many have suggested to use the fgets() function. If I proceed with that, how should I do it? – WCKennedays Jun 28 '17 at 12:58
  • @WCKennedays you are welcome. You asked a nice question (I upvoted), so I thank you too! `fgets()` is a good method. I suggest you try that on your own and *accept* an answer for this already asked question of yours. If you are having a difficult time with `fgets()`, then post a *new* question, by providing a minimal example of your attempt. Of course if you want, you can link me to this question (if you ever post it). Cheers! – gsamaras Jun 28 '17 at 13:00
  • I'm trying it out as we speak, thanks! Main struggle is because (posted the minimal example of my code) I used a `while` loop and a `switch`. I followed one of the commenter's guide: [Felix Palmen's beginners' guide away from scanf()](http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html), on part 4, using the atoi method. Problem is the validation only works at the start, and when the user puts in a valid option, the validation no longer applies cause I've moved down the code already. I'm wondering how do I slot the validation in so it covers my `while` and `switch` loop. – WCKennedays Jun 28 '17 at 22:03
1

I am assuming u are a beginner. You can use Switch Case which is used usually for creating menus and depending on the choice of the user executes the particular case. I will show u a small example.

#include<stdio.h>
#include<conio.h>
int main()
{
  int n;
  printf("Select the sports u want to do\n");
  printf("1.Tennis\n2.Karate\n3.Football\n");
  scanf("%d",&n);
  Switch(n)
  {
     case 1:printf("You chose Tennis\n");
          break;   //To prevent from all cases being executed we use 
                   //break which helps from coming out of a loop 
     case 2:printf("You chose Karate\n");
          break;

     case 3:printf("You chose Football\n");
          break;

     default:printf("Please enter an appropriate number !");
            //Cases which dont match with the input are handled by default !
  }
}

Also to make the user enter input until he wants to exit add a while loop with a variable !

I hope this helps!

Entered string here

Shaurya
  • 313
  • 1
  • 12
  • After the scanf statement, please change the Case to switch. So that there won't be any syntax error – Susarla Nikhilesh Jun 28 '17 at 11:52
  • Actually that is what I've done for my code, but the problem is when the user inputs other integers, yes the default handles it. But when the user enters a 'char' like 'a', 'asd', the code goes into an infinite loop for some reason. – WCKennedays Jun 28 '17 at 12:59
  • As far I know it must handle all cases....else u can paste ur entire code – Shaurya Jun 28 '17 at 13:11
  • I have pasted a pic of the output – Shaurya Jun 28 '17 at 13:26
  • @Shaurya I think that's because I've placed a while loop outside the switch. I want to make it as if it allows the user to re-enter a valid option. – WCKennedays Jun 28 '17 at 14:28