0

I am using c and I am a newbie.

I want to get a input (1 or 2 or 3) and I will give the user suggest;

printf("please do it\n");
printf("1. \n");
printf("2. \n");
printf("3. \n");
char opt;
scanf("%c"&opt");

if opt is not 1 or 2 or 3 then

printf("error\n");
printf("please re do it");

and all is in a while(true) loop until user enter the enter(new line charactor) to exit;

and how to do it?

I tried to create a function.

void get_order(char opt){
    switch(opt){
        case '1':break;
        case '2':break;
        case '3':break;
        default:
        printf("error\n");
        printf("please re do it"):
        char option;
        scanf("%c",&option);
        get_order(option);
    }
}

but it not work. thank you.

Rachid K.
  • 4,490
  • 3
  • 11
  • 30
user666
  • 329
  • 1
  • 7
  • 22
  • 3
    You state that this is in a `while(true)` loop, but there is no such loop in your code. You should provide a complete example (including a `main` and all included files). See https://stackoverflow.com/help/minimal-reproducible-example – William Pursell Dec 20 '21 at 14:23
  • 2
    Also read http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html – William Pursell Dec 20 '21 at 14:23
  • 2
    That is not a good approach, your code is using recursion, it will consume memory more and more while the user don't enter the correct input. Use a loop instead. – riquefr Dec 20 '21 at 14:29
  • 2
    If your compiler lets `scanf("%c"&opt");` through, turn on more warnings or change to a better compiler. – Ted Lyngmo Dec 20 '21 at 14:31
  • Related question: [Validate the type of input in a do-while loop C](https://stackoverflow.com/q/31633005/12149471) In my answer to that question, I provided a function `get_int_from_user`. That function may be useful for you, in the sense that it keeps reprompting the user for input until the user enters a valid number. However, the part about verifying that this number is between `1` and `3` would have to be added by you. – Andreas Wenzel Dec 20 '21 at 14:40
  • `scanf("%c"&opt");` -> `scanf("%c", &opt);` – ryyker Dec 20 '21 at 14:43

1 Answers1

2

That is not a good approach, your code is using recursion, it will consume memory more and more while the user don't enter the correct input. Use a loop instead. Your code should look like this:

#include <stdio.h>

int main() {
    printf("please do it\n");
    printf("1. \n");
    printf("2. \n");
    printf("3. \n");
    char opt;
    scanf("%c", &opt); //correct scanf
    scanf("%*c"); //consume the line break
    while(!(opt == '1' || opt == '2' || opt == '3')) {
        printf("error\n");
        printf("please re do it\n");
        scanf("%c", &opt); //correct scanf
        scanf("%*c"); //consume the line break
    }   
    return 0;
}
riquefr
  • 260
  • 1
  • 7