我有一个程序,它根据定义的规则接受特定的字符串,即数字运算符数字。例如:2+4-5*9/8
以上字符串是可以接受的。现在,当我输入类似2+4-a
的内容时,它再次显示可接受,这是完全不可接受的,因为根据定义的规则,数值应该只在0到9之间。我想我将不得不使用ASCII值进行检查。
请参阅以下代码:
#include <iostream>
#include <ncurses.h>
#include <string.h>
#include <curses.h>
int check(int stvalue) {
if(stvalue < 9) return(1);
else return(0);
}
main() {
int flag = 0;
char str[10];
std::cout << "Enter the string:";
std::cin >> str;
int i = 1;
int n = strlen(str);
for(i = 0; i < n - 1; i += 2) {
if(!check(str[i])) {
if(str[i + 1] == '+' || str[i + 1] == '-' || str[i + 1] == '/' || str[i + 1] == '*') flag = 1;
else {
flag = 0;
break;
}
}
}
if(flag == 1) std::cout << "String is acceptable" << std::endl;
else std::cout << "String is not acceptablen" << std::endl;
getch();
}
输出:
Enter the string:2+4-5
String is acceptable
Enter the string:3*5--8
String is not acceptable
Enter the string:3+5/a
String is acceptable
最后一个输出不应被接受。
int check(int stvalue) {
if(stvalue < 9) return(1);
else return(0);
}
这是错误的,因为ASCII图表上的数字等价物是48到57,从0到9。
你可以通过一个类似于的函数来简化验证
#include <cctype>
bool validateString(const std::string& str) {
auto compare = [](char c) {
return ((c == '+') || (c == '-') || (c == '*') || (c == '/'));
};
size_t length = str.length();
for(size_t i = 0; i < length; ++i) {
if(!(std::isdigit(str[i]) || compare(str[i])))
return false;
if(compare(str[i]) && (i <= length-1) && compare(str[i+1]))
return false;
if(compare(str[length-1]))
return false;
}
return true;
}
for(i = 0; i < n - 1; i += 2) {
您不检查字符串的最后一个字符,所以最后一个a
会通过。
请记住,strlen
不包括空字符,您不需要为此进行调整。
还要使用check(str[i] - '0')
,因为您要检查的是数字,而不是其ascii码。
最后一个大问题-
if(str[i] == '+' || str[i] ==
如果检查失败,您需要检查该字符是否是运算符,而是否是下一个运算符 默认情况下,也将flag设置为1。我把你的代码改写了一点。 进一步重写的代码,捕获重复的数字或运算符 这里有一些提示: 如果您的输入总是在个位数和运算符之间交替,您可以使用以下内容: 数字是字符类型的,所以请检查它们的ASCII值,看看它们是否是数字。 ASCII值,如果0是48,9是57…而不是9。所以如果(stvalue<9)返回(1); 应该是,如果(stvalue<=57)返回(1); 顺便说一句,这种方法可能有效,但其他答案是解决这个问题的更成熟的方法。n
添加2,因此它将检查3+
和5/
,但a
永远不会被查看for (int i = 0; i < n; i++) // read *every* character
{
if (i % 2 == 0)
{
// you are looking at a character with an even index
}
else
{
// you are looking at a character with an odd index
}
}
%
运算符将左操作数除以右操作数,得到该除法的余数。check
函数检查的是char
值是否小于9,而不是char
值是否表示数字字符。您可以包含<cctype>
标头,并使用isdigit
而不是check
函数,该函数检查输入是否代表数字字符。