定義された規則、つまり数値演算子番号に従って特定の文字列を受け入れるプログラムがあります。例えば: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 acceptable\n" << 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
最後の出力は受け入れられません。