【发布时间】:2021-01-13 16:28:03
【问题描述】:
程序会提示用户输入一个简单的表达式。拆分字符串并分配变量后,我想检查用户输入的内容是否为整数,以便可以在 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;
}
}
【问题讨论】:
-
这能回答你的问题吗? Input validation of an Integer using atoi()
-
不确定,所以我不能要求用户输入多个,必须是一个条目。我需要检查运算符以查看是否有一个,这就是为什么我使用 strchr() 进行 for 循环,因为稍后我将使用它来分解字符串并检索两个变量。我注意到只要我有一个可以工作的运算符,我就可以输入字母。我感到困惑的是如何检查或将指针转换为布尔值当插入字母并使用 atoi() 时,我得到一个 0 并将其存储在 num1 中,但是如果用户输入 0 它应该也是有效的,0 - 22 是有效的条目。
-
atoi不适合验证。请改用strtol。它在链接的帖子中进行了解释。 -
使用 strtol 会将字母条目转换为 0,但是如果用户输入 0 它可能是有效的......使用 if 语句检查 0 可能会使有效条目无效。跨度>
-
花时间完整仔细地阅读您可用的信息。您已经获得了手册页和带有示例的帖子。函数的返回值不是唯一要检查的。 man page 告诉您如何检查无效号码:
If there were no digits at all, strtol() stores the original value of nptr in *endptr (and returns 0). In particular, if *nptr is not '\0' but **endptr is '\0' on return, the entire string is valid.
标签: c validation pointers boolean strtok