如何在C中识别字符串中的减法?

问题描述 投票:0回答:1

我正在尝试使用 PIC18F46K22 微控制器和 UART 制作一个简单的计算器。然而,它仅适用于添加两个数字,即使 strstr 比较并找到“+”/“-”。

有人可以发现问题吗?

代码:

`#include <xc.h>             //-- for XC8 compiler
#include <stdio.h>          //   for printf
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

#define _XTAL_FREQ 32E6

typedef struct
{
    char data[32];
    char full;
    int  index;
} mailbox;


void main(void)
{ 
    
    while(1)
    {
        if(g_mail.full)
        {
            while(!TX1IF);
            char *ptr;
            int num1, num2;
            char operator;
            
  
            // Determine the operator using strstr
            if (strstr(g_mail.data, "+")) {
                operator = '+';
            } else if (strstr(g_mail.data, "-")) {
                operator = '-';
            }


            int result = 0;

            // Perform the calculation
            if (operator == '+') {
                result = num1 + num2;
            } else if (operator == '-') {
                result = num1 - num2;
            }

            // Prepare the result string
            char resultStr[16];
            sprintf(resultStr, "%d", result); // Convert result to a string

            // Send each character in the result string
            for (int i = 0; i < strlen(resultStr); i++) {
                while (!TXSTAbits.TRMT); // Wait for TX buffer to be ready
                TXREG = resultStr[i]; // Send character
            }

            g_mail.full = 0; // Reset mailbox flag
            memset(g_mail.data, 0, sizeof(g_mail.data)); // Clear the data array
        }
    }
}

感谢大家的帮助和提示!

我尝试过更改语法和一些不同的方法,但没有任何效果。聊天也找不到问题,同样的答案写得有点不同。

arrays c string microcontroller pic18
1个回答
0
投票

您认得

+
-
就好了;问题似乎是您无法识别号码的数字。你可以这样做:

if (sscanf(g_mail.data, "%d +%d", &num1, &num2) == 2) {
    result = num1 + num2;
} else if (sscanf(g_mail.data, "%d -%d", &num1, &num2) == 2) {
    result = num1 - num2;
} else {
    fprintf(stderr, "Calculation '%s' not recognized\n", g_mail.data);
    break;
}
© www.soinside.com 2019 - 2024. All rights reserved.