[英]How to get a input with prompt using scanf?
I am using c and I am a newbie.我正在使用 c,我是新手。
I want to get a input (1 or 2 or 3) and I will give the user suggest;我想得到一个输入(1或2或3),我会给用户建议;
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如果 opt 不是 1 或 2 或 3 则
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;并且一切都在一个while(true)循环中,直到用户输入
enter(new line charactor)
退出;
and how to do it?怎么做?
I tried to create a function.我试图创建一个 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.
谢谢你。
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.这不是一个好方法,您的代码正在使用递归,当用户没有输入正确的输入时,它将越来越多地消耗 memory。 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;
}
google for c string functions.谷歌 c 字符串函数。
strcmp
or you scanf
for an int then u can do strcmp
或者你scanf
一个 int 然后你可以做
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 switch (i): case 1: 你的代码 case 2: 你的代码 case 3: 你的代码
and in the different switches u give the int the number that u want so for example at case 3 (int == 3)并且在不同的开关中,你给 int 你想要的数字,例如在 case 3 (int == 3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.