C++ program to accept a string according to a particular rule (num opr num) -
C++ program to accept a string according to a particular rule (num opr num) -
i have programme accepts particular string according defined rule, i.e., number operator number. example:2+4-5*9/8
the above string acceptable. when input 2+4-a
, 1 time again showing acceptable not acceptable number value should range 0 9 according rule defined. think have utilize ascii values check.
refer code below:
#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 string:"; std::cin >> str; int = 1; int n = strlen(str); for(i = 0; < n - 1; += 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 acceptable" << std::endl; else std::cout << "string not acceptable\n" << std::endl; getch(); }
output:
come in string:2+4-5 string acceptable come in string:3*5--8 string not acceptable come in string:3+5/a string acceptable
the lastly output should not acceptable.
for(i = 0; < n - 1; += 2) {
you don't check lastly character of string, final a
gets through.
remember strlen
not include null char, dont need adjust it.
also utilize check(str[i] - '0')
since want check on number , not ascii code.
final big issue -
if(str[i] == '+' || str[i] ==
if check fails, you need check if char operator, not next one, above. output
also set flag 1 default. have rewriten code little.
further rewritten code catches repeated digits or operators
c++
Comments
Post a Comment