gpt4 book ai didi

c - 如何在 c 中创建灵活的占位符表达式 (%d %s %d)?

转载 作者:太空宇宙 更新时间:2023-11-03 23:22:59 24 4
gpt4 key购买 nike

该程序可让您输入数学问题,例如:

Bob has 1 apple and Mike 2. What is the sum?

程序然后理解单词“sum”并将两个数字相加。至少那是我想要实现的目标。它不起作用,因为我得到了非常大的数字。我怀疑表达式 %d %s %d 不够灵活,只有在问题是:

1 sum 2

顺序似乎很重要。那么我该如何让它变得灵活,以便顺序无关紧要呢?

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

int main() {
char question[100];
char buffer[100];
int result;
int n1, n2;
int operation;

printf ("Your mathematical question: ");

fgets(question, sizeof(question), stdin);
fflush(stdin);

if(strstr(question, "sum") || strstr(question, "add")){
operation = 0;
}

sscanf(question, "%d %s %d", &n1, buffer, &n2);

printf ("%d %d \n", n1, n2);

switch(operation) {
case 0: result = n1 + n2;
break;
}

printf ("%d", result);
return(0);
}

最佳答案

尝试使用 strtok 将您的输入字符串拆分为运算符和操作数列表。问题在于,在表达数学短语时,英语等自然语言没有运算符和操作数的正式顺序,而您的程序需要这样。

将输入拆分为运算符和操作数可让您按所需顺序匹配它们。

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

typedef enum
{
NO_OP,
ADDITION,
/* Add new operators here. */
} operator_t;

/* One operator plus two operands. */
#define NUMBER_OF_ITEMS 3

int main()
{
char question[100];
char buffer[100];
char *token;

int result = 0;
/* Extend this to allow more complex sentences with multiple operations. */
int operands[2];
int* nextOperand = &operands[0];
int itemCount = 0;
/* Turn this into an array to extend the parser. */
operator_t operator = NO_OP;

printf ("Your mathematical question: \r\n");

fgets(question, sizeof(question), stdin);

/* Tokens are seperated by SPACES in this example. */
const char delims[] = " ";

/* Get the first token. */
token = strtok(question, delims);

/* Walk through all tokens in the question string. */
while((token != NULL)&&(NUMBER_OF_ITEMS > itemCount))
{
/* use strcmp to avoid matches on words like 'summertime'. */
if((0 == strcmp(token, "sum")) || (0 == strcmp(token, "add")))
{
operator = ADDITION;
itemCount++;
}
else
{
/* Check that one integer can be parsed from the token. */
if(1 == sscanf(token, "%d", nextOperand))
{
nextOperand++;
itemCount++;
}
}

/* Find the next token. */
token = strtok(NULL, delims);
}

/* Perform the operation, if possible. */
if((NUMBER_OF_ITEMS == itemCount) && (NO_OP != operator))
{
switch(operator)
{
case ADDITION:
result = operands[0] + operands[1];
printf("The answer to your question (%d + %d) is %d.\r\n",
operands[0], operands[1], result);
break;
default:
printf("Oops, please ask my programmer to do some debugging.");
break;
}

}
else
{
printf ("I did not understand your question.\r\n");
}
}

请注意,您需要添加更多的错误检查以获得良好的稳健性,但上面的代码应该有助于说明如何解决问题。

然后您可以使用类似 Reverse Polish Notation 的东西扩展解析器的功能。

关于c - 如何在 c 中创建灵活的占位符表达式 (%d %s %d)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34313271/

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