我写了一个C程序,当输入以下列格式给出时,该程序有sum
,sub
,mul
和div
命令:
总和2 3
5sub 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();
}
答案 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();
}