繁体   English   中英

在 switch 语句之前输入字符串并使用 switch 语句比较 c 中的字符串

[英]Input strings before switch statement & compare strings in c using switch statement

我是一个愿意学习的学生 c. 我的问题是,用户需要输入一个形状名称,该形状名称应该通过 switch 语句。 但我不能那样做。 因为我不知道如何将字符串传递给 switch 语句。 那么有人可以帮助我吗? 我将添加我的代码以供参考。

#include <stdio.h>

int main(){
int h,w,r,l,area;
char shape[8];

printf("Please select a shape = ");
scanf("%s",&shape);

switch(shape[8]){
case 'circle':
    printf("Enter value for radius = ");
    scanf("%d",&r);

    area = 3.14*r*r;

    printf("Area of circle is = %d",area);
    break;
case 'square':
    printf("Enter value for width = ");
    scanf("%d",&w);

    area = w*w;

    printf("Area of square is = %d",area);
    break;
case 'rectangle':
    printf("Enter value for width = ");
    scanf("%d",&w);
    printf("Enter value for height = ");
    scanf("%d",&h);

    area = w*h;

    printf("Area of rectangle is %d",area);
    break;
case 'triangle':
    printf("Enter value for length = ");
    scanf("%d",&l);
    printf("Enter value for height = ");
    scanf("%d",&h);

    area = 1/2*l*w;

    printf("Area of triangle is = %d",area);
    break;
default:
    printf("Invalid Shape");

}
return 0;

}

使用switch()不是处理此问题的推荐方法——但您可以这样做。 您将创建一个查找表(有效形状的字符串文字数组),当您检查用户输入是否为有效形状时,您将保存与有效形状对应的索引并将索引作为switch()传递switch()变量。 那么您的案例将是整数值,您可以采取适当的行动。

例如,您可以使用以下命令创建一个简单的查找表:

/* lookup-table (array of pointers to string-literals) */
const char *shapes[] = { "circle", "square", "rectangle", "triangle" };

/* if you need a constant, #define one (or more) */
#define NSHAPES (int)(sizeof shapes / sizeof *shapes)

其中NSHAPESshapes数组中的shapes (您可以只使用4 ,但避免硬编码数字... MagicNumbers ...)

然后您可以创建一个简单的函数来循环比较用户输入的形状与查找表中的每个形状的数组,如果找到则返回索引,如果未找到则返回-1 ,例如

/* function to validate shape is one of the valid shapes */
int validshape (const char *shape)
{
    for (int i = 0; i < NSHAPES; i++)           /* loop over each shape */
        if (strcmp (shape, shapes[i]) == 0)     /* compare shape with shapes[i] */
            return i;                           /* return index if found */
    
    return -1;                                  /* return -1 if no match found */
}

然后在main() ,您获取用户输入并简单地将字符串传递给函数并进行验证,例如

    int shape = -1;
    ...
        shape = validshape (line);              /* get shape index (-1 if none) */
        if (shape != -1)                        /* check index is valid  */
            break;                              /* (break loop if valid) */
        /* otherwise handle error, show allowed */
        fputs ("  error   : invalid input.\n", stderr);

使用shape的有效索引,您可以然后switch(shape) ,例如

    fputs ("\nvalid : ", stdout);
    switch (shape) {
        case 0: puts (shapes[0]); break;
        case 1: puts (shapes[1]); break;
        case 2: puts (shapes[2]); break;
        case 3: puts (shapes[3]); break;
        default: fputs ("oops -- shouldn't get here\n", stderr);
    }

您可以更新每个案例来处理您的算术。

完整版本(使用fgets()获取用户输入,因此新的 C 程序员不会陷入与使用scanf()获取用户输入相关的许多陷阱,您可以这样做:

#include <stdio.h>
#include <string.h>

/* lookup-table (array of pointers to string-literals) */
const char *shapes[] = { "circle", "square", "rectangle", "triangle" };

/* if you need a constant, #define one (or more) */
#define NSHAPES (int)(sizeof shapes / sizeof *shapes)
#define MAXC 1024

/* simple function to show allowed shapes */
void showallowed (void)
{
    fputs ("  allowed :", stdout);              /* output prefix */
    for (int i = 0; i < NSHAPES; i++)           /* loop over each shape */
        printf (" %s", shapes[i]);              /* output shape */
    putchar ('\n');                             /* tidy up with newline */
}

/* function to validate shape is one of the valid shapes */
int validshape (const char *shape)
{
    for (int i = 0; i < NSHAPES; i++)           /* loop over each shape */
        if (strcmp (shape, shapes[i]) == 0)     /* compare shape with shapes[i] */
            return i;                           /* return index if found */
    
    return -1;                                  /* return -1 if no match found */
}

int main (void) {
    
    char line[MAXC];                            /* buffer to hold all user-input */
    int shape = -1;
    
    while (1) { /* loop continually */
        fputs ("\nenter shape: ", stdout);      /* output prompt for shape */
        if (!fgets (line, MAXC, stdin))         /* validate user input */
            return 1;
        line[strcspn (line, "\n")] = 0;         /* trim \n from end of line */
        shape = validshape (line);              /* get shape index (-1 if none) */
        if (shape != -1)                        /* check index is valid  */
            break;                              /* (break loop if valid) */
        /* otherwise handle error, show allowed */
        fputs ("  error   : invalid input.\n", stderr);
        showallowed();
    }
    
    fputs ("\nvalid : ", stdout);
    switch (shape) {
        case 0: puts (shapes[0]); break;
        case 1: puts (shapes[1]); break;
        case 2: puts (shapes[2]); break;
        case 3: puts (shapes[3]); break;
        default: fputs ("oops -- shouldn't get here\n", stderr);
    }
}

示例使用/输出

$ ./bin/validshapes

enter shape: apples
  error   : invalid input.
  allowed : circle square rectangle triangle

enter shape: squares
  error   : invalid input.
  allowed : circle square rectangle triangle

enter shape: rectangle

valid : rectangle

如果您还有其他问题,请告诉我。

不幸的是,C 不支持在 case 语句中传递字符串,因此为了避免这种情况,您可以将 if-else 与strcmp()或者为每个形状分配一个数字,然后将其传递给 switch 语句。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM