c - 我如何比较这个变量以便可以在 switch 语句中使用它?

标签 c

我只想允许字符串或整数输入,但我似乎无法弄清楚,这就是我到目前为止所拥有的..

#include <string.h>
#include <stdio.h>
#include <limits.h>
#include <ctype.h>
#include <stdlib.h>
#define maxL 9182

int main() {
    char menuOption;
    char cmd[10];

// DECLARE FUNCTIONS TO BE USED IN MENU


    float circle() {
        float numbers;
        float calcFloat;


        printf("\n\nYou've selected a circle!\n\n");
        printf("Enter in a value between 1.00 and 1000.00: ");
         scanf("%f%*c",&calcFloat);
        printf("You've entered %f\n", calcFloat);

        numbers = 2*calcFloat*3.14159;

        printf("The circumference of your circle is: %f\n\n\n", numbers);

    }

    float sphere() {
        float sphere;
        float calcSphere;


        printf("\n\nYou've selected a sphere!\n\n");
        printf("Enter in a value between 10.5 and 1024.00: ");
         scanf("%f%*c",&calcSphere);
        printf("You've entered %f\n", calcSphere);

        sphere = (4/3)*calcSphere*calcSphere*calcSphere*3.14159;

        printf("The volume of a sphere with your value is: %.2f\n\n\n", sphere);

    }

    char checkInput(char input) {

        if ((strcmp(input, "0") == 0) || (strcmp(input, "zero") == 0)) {
        return 0;
        }
    }

// END OF FUNCTIONS


// CREATE AND SHOW MENU AND RECEIVE INPUT TO DIRECT TO PROPPER FUNCTION.


    for (;;) {

        printf("Menu: \n" 
        "(0)Circle\n" 
        "(1)Sphere\n" 
        "(2)Palindrome\n" 
        "(3)Shuffle\n" 
        "(4)Quit\n");

        printf("Select your choice!: ");
        scanf("%c", cmd);           

        switch (checkInput(tolower(cmd))) {

            case 0:
                circle();
            break;

            case 1:
                sphere();
            break;
        }
    }

// END OF SWITCH STATEMENT AND MENU
}

我想让人们在 scanf 中输入 0 或零以减少用户错误,谢谢!

最佳答案

getline 函数可让您将字符串存储到 cmd 中。

然后,您可以将字符串与 strcmp 进行比较

if ((strcmp(cmd, "0") == 0) || (strcmp(cmd, "zero") == 0)) {
    circle();
} else if ((strcmp(cmd, "1") == 0) || (strcmp(cmd, "one") == 0)) {
    sphere();
}

关于c - 我如何比较这个变量以便可以在 switch 语句中使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15541116/

相关文章:

c - C 查询中的固定数组大小

c - 是什么导致 "incompatible implicit declaration"警告?

c - 将 long 和 time_t 的大小定义为 4bytes

C - 赋值后访问结构体属性会导致段错误

c - OpenMP 并行 'for' 无法正常工作

c - 使用 printf 以不同的精度打印 float

c++ - Webkit GTK : Getting HTTP response

c - 使用各种方法无法使系统蜂鸣声在 C 中工作

c - sprintf() 段错误

c - 如何在 linux(gcc) 中将 int 转换为 char/string,反之亦然?