Home > front end >  How to get a input with prompt using scanf?
How to get a input with prompt using scanf?

Time:12-20

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.

CodePudding user response:

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;
}

CodePudding user response:

google for c string funktions. strcmp or you scanf for an int then u can do

while(int == wantet nuber){ printf("Nuber exseptet); ") } else{ printf("number not exseptet"); return 0; }

or u do a switch case

switch (i): case 1: your code case 2: your code case 3: your code

and in the diverent switches u give the int the nuber that u want so for exsample at case 3 (int == 3)

  • Related