跳过C中的参数

时间:2016-09-16 02:16:17

标签: c

我写了一个C程序,当输入以下列格式给出时,该程序有sumsubmuldiv命令:

  

总和2 3
  5

     

sub 4 3
  1

     

...

我能够完成每项操作。但是,最后,当我需要退出程序时,我应该只给出bye命令作为输入,程序应该停止执行。但是,只有当我提供2个数字和bye时,该程序才会退出。如何仅使用bye退出程序?

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

void main()
{
    int op1,op2;                              
    char opera[3];                          
    do
    {
        printf("please enter input(operator operand1 operand2)"); 

        if ((opera[3]>='a' && opera[3]<='z')|| (opera[3]>='A' && opera[3]<='Z'))  
        {
            printf("The operands are not valid", opera[3]);
        }
        scanf("%s %d %d",opera,&op1,&op2); 

        if (strcmp(opera, "bye") == 0)
        {
            printf("Bye");
            exit(0);
        }

        if (strcmp(opera, "sum") == 0)
        {
            printf("%d",op1+op2);
        }

        else if (strcmp(opera, "sub") == 0)
        {
            printf("%d",op1-op2);
        }

        else if (strcmp(opera, "mul") == 0)
        {
            printf("%d",op1*op2);
        }

        else if (strcmp(opera, "div") == 0)
        {
            if (op2 == 0)
            {
                printf("The expression is invalid");
            }
            else
            {
                printf("%d",op1/op2);
            }
        }
    }
    while (opera != getchar());
    getch();
}

1 个答案:

答案 0 :(得分:1)

opera[]中有缓冲区溢出,而您没有正确读取参数。尝试更像这样的东西:

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>

void main()
{
    int op1, op2;
    char opera[4];

    do
    {
        printf("please enter input (operator operand1 operand2): ");

        if (scanf("%3s", opera) != 1)
            continue;

        if (strcmp(opera, "bye") == 0)
        {
            printf("Bye");
            exit(0);
            return;
        }

        if (scanf("%d %d", &op1, &op2) != 2)
        {
            printf("The operands are not valid\n");
            continue;
        }

        if (strcmp(opera, "sum") == 0)
        {
            printf("%d\n", op1+op2);
        }

        else if (strcmp(opera, "sub") == 0)
        {
            printf("%d\n", op1-op2);
        }

        else if (strcmp(opera, "mul") == 0)
        {
            printf("%d\n", op1 * op2);
        }

        else if (strcmp(opera, "div") == 0)
        {
            if (op2 == 0)
            {
                printf("The expression is invalid\n");
            }
            else
            {
                printf("%d\n", op1 / op2);
            }
        }

        else
        {
            printf("The operator is invalid\n");
        }
    }
    while (1);

    getch();
}