gpt4 book ai didi

在 C : RPN interpreter 中将字符串的数字成员(char 类型)转换为 int 类型

转载 作者:太空宇宙 更新时间:2023-11-04 02:33:17 25 4
gpt4 key购买 nike

我目前正尝试在 C 中创建一个逆波兰符号解释器,使用使用 struct 实现的堆栈。它应该采用所有个位数的值 (0-9) 和运算符 +-*/,并通过退出程序拒绝所有其他人。

我试图捕获整个表达式,因为它是作为字符串输入的,类型为 char,但是当我使用 isdigit() 时,它总是返回一个非零函数(IE ,它不是数字),即使它对用户来说是数字。我相信这是因为字符串是 char 类型的事实,但我认为我不能使用其他任何东西,否则在输入运算符时我会收到错误消息。

错误如下:假设我在函数中输入"11+"。在调试中,我可以看到这出现在 watch 中。继续执行程序,我看到 isdigit () 返回了 1 而不是 0,因此 if 语句条件满足,程序以 exit(1) 退出; IDE 没有提供具体的错误消息。

有没有办法实现仅将字符串的“数字”转换为 int 类型,还是我必须做其他事情?

这是函数。虽然它仍然是原始的和未完成的,但它显示了错误:

void parseRPN(TopStack *st)
{
char Input[50];
int i;
do{
printf("please enter an expression in single-digit integers"
"using Reverse Polish notation:");
scanf("%s",&Input);
if (sizeof(Input)/sizeof(int)>=50)
{
printf("that expression was too large for the RPN engine to handle!"
"please break it down into smaller sub-tasks.\n");
fflush(stdin);
continue;
}
break;
}while(true);

for (i=0;i<50;i++)
{
int ErrorDetect=isdigit(Input[i]);
if (ErrorDetect==0 && (Input[i]) != '+' || '-' || '*' || '/')
{
printf("Error: Invalid operand to RPN\nExiting...");
exit(1);
}
else printf("great success!");
}
}

最佳答案

当然是无意中使用了 ||
@J. Piquard也对此发表评论

// if (ErrorDetect==0 && (Input[i]) != '+' || '-' || '*' || '/')
if (ErrorDetect==0 && Input[i] != '+' || Input[i] != '-' ||
Input[i] != '*' || Input[i] != '/')

或者类似的东西。为清楚起见,建议添加 ()。我认为 OP 需要不同的逻辑。

if (ErrorDetect || (Input[i] != '+' && Input[i] != '-' && 
Input[i] != '*' && Input[i] != '/'))

可能存在其他编码问题,例如:

char Input[50];
// scanf("%s",&Input);
scanf("%49s",&Input);

关于在 C : RPN interpreter 中将字符串的数字成员(char 类型)转换为 int 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40687025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com