繁体   English   中英

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM