验证用户的输入以检查输入的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函数。 您可以在以下链接中查看更多详细信息:strtol - c++reference