【问题标题】:How to get a input with prompt using scanf?如何使用scanf获取提示输入?
【发布时间】:2022-01-22 03:39:39
【问题描述】:

我正在使用 c,我是新手。

我想得到一个输入(1 或 2 或 3),我会给用户建议;

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

如果 opt 不是 1 或 2 或 3 则

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

所有都在一个while(true)循环中,直到用户输入enter(new line charactor)退出;

怎么做?

我试图创建一个函数。

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

但它不起作用。 谢谢。

【问题讨论】:

  • 您声明这是在while(true) 循环中,但您的代码中没有这样的循环。您应该提供一个完整的示例(包括main 和所有包含的文件)。见stackoverflow.com/help/minimal-reproducible-example
  • 这不是一个好方法,你的代码使用递归,当用户没有输入正确的输入时,它会越来越消耗内存。请改用循环。
  • 如果您的编译器允许scanf("%c"&opt"); 通过,请打开更多警告或更改为更好的编译器。
  • 相关问题:Validate the type of input in a do-while loop C 在我对该问题的回答中,我提供了一个函数get_int_from_user。该功能可能对您有用,因为它会不断提示用户输入,直到用户输入有效数字。但是,验证此号码是否介于13 之间的部分必须由您添加。

标签: c scanf


【解决方案1】:

这不是一个好方法,您的代码使用递归,当用户没有输入正确的输入时,它会越来越多地消耗内存。请改用循环。您的代码应如下所示:

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

【讨论】:

  • 如果用户输入了多个字符,scanf("%*c"); 行将不会使用换行符。
  • 最好使用scanf( " %c", &amp;opt ) 跳过任何前导空格。当然,最好不要为此使用scanf
  • 不使用scanf应该用什么?@JohnBode
  • 您可以使用其他类型的输入处理程序,但使用起来有点困难。像getlinegets 和其他一些人。
  • @riquefr 你不应该推荐gets
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-24
  • 2013-01-16
  • 1970-01-01
  • 2021-08-15
  • 1970-01-01
相关资源
最近更新 更多