验证用户的输入以检查输入在 C 中的格式是否正确

Validate user's input to check if input is in the right format in C

程序将提示用户输入一个简单的表达式。拆分字符串并分配变量后,我想检查用户输入的内容是否为整数,以便可以在 switch 语句中进行计算。验证 num1 和 num2 中的数据以确保它们是整数而不是字母或任何其他字符的最佳方法是什么。

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

/*This function will display the user's desired expression to be calculated */
char* expressionDisplay(char* input)
{
    char *str = input;
    printf("The expression entered is: %s\n", str);
    
}

int main()
{
    char str[50];
    char operator[6] = "+-*/%";
    int num1,num2;
    char calculation;
    char *oldstr = malloc(sizeof(str));
    printf("This program will solve a simple expression in the format 'value' 'operator' 'value'\n ");
    printf("Example 2+6 or 99 * 333\n");
    printf("Enter the simple expression to be calculated: \n"); 
    scanf("%[^\n]%*c", str);  //this will scan the whole string, including white spaces
    strcpy(oldstr, str);
    for(int i = 0; i < strlen(operator); i++)
    {

        char *position_ptr = strchr(str, operator[i]);
        int position = (position_ptr == NULL ? -1 : position_ptr - str);    
        if(str[position] == operator[i])
        {
            calculation = operator[i];
            char *num1_ptr = strtok(str, operator);
            int num1 = atoi(num1_ptr);
            char * num2_ptr = strtok(NULL, operator);
            int num2 = atoi(num2_ptr);
            break;
        }else
        
        calculation = position;
    }

    switch(calculation)
    {
        case '+':
        expressionDisplay(oldstr);
        printf("Sum\n");
        break;
        case '-':
        expressionDisplay(oldstr);
        printf("Subtract\n");
        break;
        case '*':
        expressionDisplay(oldstr);
        printf("Multiply\n");
        break;
        case '/':
        expressionDisplay(oldstr);
        printf("Division\n");
        break;
        case '%':
        expressionDisplay(oldstr);
        printf("Modulus\n");
        break;
        default:
        printf("Sorry unable to calculate the expression entered. Try again.\n");
        printf("Enter a simple expression - number operator number - ");
        break;
    }
}

这种情况下可以使用标准c库的strtol函数。 你可以在 link 看到更多细节:strtol - c++reference.