c - 验证用户的输入以检查输入在 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;
}
}
解决方案
在这种情况下,您可以使用strtol
标准 c 库的功能。您可以在此链接中查看有关它的更多详细信息:strtol-c++reference。
推荐阅读
- c - 这些有什么区别?
- c# - EF Core - What is the correct configuration?
- laravel - laravel blade syntax for loop how to call iteration index inside laravel helper functions
- javascript - Cannot assign retrieved json to object in ReactJS using setState and then retrieve it from state
- linux - 如何使用 `gcc` 编译和运行 C 程序?
- service - Anylogic - 根据源在延迟块中设置多个延迟时间
- python - 有人可以在 Python 中解释这个 dict().get 函数吗?
- javascript - 如何访问其键也是对象的 javascript 对象值(Azure AD SSO,单授权流)
- mysql - MySQL/Clickhouse 组合/RANK 选择的结果与一组标签并保持其余的唯一
- node.js - 无法获得在 angular/node.js 中工作的发布路线