Thread: Number or character?

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    22

    Number or character?

    how can i check if the user typed a number(int) or a char?
    maybe there is a function or something?

  2. #2
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  3. #3
    Registered User
    Join Date
    Nov 2005
    Posts
    22
    i didnt find there nothing i wanted.
    i will explain my problem with more details:
    i am doing a program that solves a math exercises with order of arithmetic operations for example: 2*(7-6*4+(11-6)+(14-5))
    now, the user types number or character(*,-,+,/) i have a struct that contains one int variable and one char variable the user types character or number and i need to put the char/num to the proper variable, number to integer and character to char.
    so, how can i know what the user typed number or character?
    thanks a lot to your attension.

  4. #4
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,079
    Accept the entire input into a character array. Then do isdigit() on each element of the array. If it returns true, then atoi() the digit and put it into an integer variable.
    Sent from my iPadŽ

  5. #5
    Registered User
    Join Date
    Nov 2005
    Posts
    22
    so if i understood well char array can contains char and integer but isdigit() finds if its number if number it returns true.
    and the second function changes the digit to normal integer number.
    am i right?

  6. #6
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,079
    Character Array can hold characters.

    This is where the difference between 9 and '9' matter.

    isDigit is a function to which you pass a single character. If the character is a number (ie. the characters '1', '2', '3', '4'... etc) it returns true. Then you must use atoi() which converts a character digit into it's appropriate integer. ... but this integer can't be put back into the character array.
    Sent from my iPadŽ

  7. #7
    Registered User
    Join Date
    Oct 2005
    Posts
    38
    Code:
    //  GENERIC PARSER
    
    #include <iostream>
    #include <cstdlib>
    #include <cctype>
    #include <cstring>
    
    using namespace std;
    
    enum types { DELIMITER = 1, VARIABLE, NUMBER};
    
    const int NUMVARS = 26;
    
    template <class PType> class parser {
             char *exp_ptr; //points to the expression
             char token[80]; //holds current token
             char tok_type; //holds token's type
             PType vars[NUMVARS]; //holds variable's values
             
             void eval_exp1(PType &result);
             void eval_exp2(PType &result);
             void eval_exp3(PType &result);
             void eval_exp4(PType &result);
             void eval_exp5(PType &result);
             void eval_exp6(PType &result);
             void atom (PType &result);
             void get_token(), putback();
             void serror(int error);
             PType find_var(char *s);
             int isdelim(char c);
             public:
                    parser();
                    PType eval_exp(char *exp);
    };
    
    //parser constructor
    template <class PType> parser<PType>::parser() {
             int i;
             exp_ptr = NULL;
             for(i=0; i<NUMVARS; i++) vars[i] = (PType) 0;
    }
    
    //parser entry point
    template <class PType> PType parser<PType>::eval_exp(char *exp) {
             PType result;
             exp_ptr = exp;
             
             get_token();
             if(!*token) {
                         serror(2); //No Expression present
                         return (PType) 0;
             }
             eval_exp1(result);
             if(*token) serror(0); //Last Token Must Be NULL
             return result;
    }
    
    //Process an assignment
    template <class PType> void parser<PType>::eval_exp1(PType &result) {
             int slot;
             char ttok_type;
             char temp_token[80];
             if(tok_type==VARIABLE) {
                                    strcpy(temp_token, token);
                                    ttok_type = tok_type;
                                    slot = toupper(*token) - 'A';
                                    get_token();
                                    if(*token != '=') {
                                              putback();
                                              strcpy(token, temp_token);
                                              tok_type = ttok_type;
                                    }
                                    else {
                                         get_token();
                                         eval_exp2(result);
                                         vars[slot] = result;
                                         return;
                                    }
             }
             eval_exp2(result);
    }
    
    //Add Or Subtract Two Terms
    template <class PType> void parser<PType>::eval_exp2(PType &result) {
             register char op;
             PType temp;
             eval_exp3(result);
             while((op = *token) == '+' || op == '-') {
                       get_token();
                       eval_exp3(temp);
                       switch(op) {
                                  case '-':
                                       result = result - temp;
                                       break;
                                  case '+':
                                       result = result + temp;
                                       break;
                       }
             }
    }
    
    //Multiply Or Divide Two Factors
    template <class PType> void parser<PType>::eval_exp3(PType &result) {
             register char op;
             PType temp;
             eval_exp4(result);
             while((op = *token) == '*' || op == '/' || op == '%') {
                       get_token();
                       eval_exp4(temp);
                       switch(op) {
                                  case '*':
                                       result = result * temp;
                                       break;
                                  case '/':
                                       result = result / temp;
                                       break;
                                  case '%':
                                       result = (int) result % (int) temp;
                                       break;
                       }
             }
    }
    
    //Process an exponent
    template <class PType> void parser<PType>::eval_exp4(PType &result) {
             PType temp, ex;
             register int t;
             eval_exp5(result);
             if(*token == '^') {
                       get_token();
                       eval_exp4(temp);
                       ex = result;
                       if (temp == 0.0) {
                                result = (PType) 1;
                                return;
                       }
                       for (t=(int)temp-1; t>0; --t) result = result * ex;
             }
    }
    
    //Evaluate a unary + or -
    template <class PType> void parser<PType>::eval_exp5(PType &result) {
             register char op;
             op = 0;
             if((tok_type == DELIMITER) && *token == '+' || *token == '-') {
                          op = *token;
                          get_token();
             }
             eval_exp6(result);
             if(op=='-') result = -result;
    }
    
    //Processed a parenthesized expression.
    template <class PType> void parser<PType>::eval_exp6(PType &result) {
             if((*token == '(')) {
                        get_token();
                        eval_exp2(result);
                        if(*token != ')') serror(1);
                        get_token();
             }
             else atom(result);
    }
    
    //Get The Value Of A Number Or A Variable
    template <class PType> void parser<PType>::atom(PType &result) {
             switch(tok_type) {
                              case VARIABLE:
                                   result = find_var(token);
                                   get_token();
                                   return;
                              case NUMBER:
                                   result = (PType) atof(token);
                                   get_token();
                                   return;
                              default:
                                      serror(0);
             }
    }
    
    //Return A Token To The Input Stream
    template <class PType> void parser<PType>::putback() {
             char *t;
             t = token;
             for(; *t; t++) exp_ptr--;
    }
    
    //Display Syntax Error
    template <class PType> void parser<PType>::serror(int error) {
             static char *e[] = {
                    "Syntax Error",
                    "Unbalanced Parentheses",
                    "No Expression Present"
             };
             cout << e[error] << endl;
    }
    
    //Obtain The Next Token
    template <class PType> void parser<PType>::get_token() {
             register char *temp;
             tok_type = 0;
             temp = token;
             *temp = '\0';
             if(!*exp_ptr) return; //end of expression
             while(isspace(*exp_ptr)) ++exp_ptr; //skip over the blanks
             if (strchr("+-*/%^=()", *exp_ptr)) {
                                     tok_type = DELIMITER;
                                     //advance to next char
                                     *temp++ = *exp_ptr++;
             }
             else if (isalpha(*exp_ptr)) {
                  while(!isdelim(*exp_ptr)) *temp++ = *exp_ptr++;
                  tok_type = VARIABLE;
             }
             else if (isdigit(*exp_ptr)) {
                  while(!isdelim(*exp_ptr)) *temp++ = *exp_ptr++;
                  tok_type = NUMBER;
             }
             *temp = '\0';
    }
    
    template <class PType> int parser<PType>::isdelim(char c) {
             if(strchr(" +-/*%^=()", c) || c==9 || c=='\r' || c==0) {
                         return 1;
             }
             return  0;
    }
    
    //Return True If c Is A Delimiter
    template <class PType> PType parser<PType>::find_var(char *s) {
             if(!isalpha(*s)) {
                              serror(1);
                              return (PType) 0;
             }
             return vars[toupper(*token) - 'A'];
    }
    
    int main() {
        char expstr[80];
        parser<double> ob;
        cout << "Enter A period to stop\n";
        for(;;) {
                cout << "Enter expression: ";
                cin.getline(expstr, 79);
                if (*expstr=='.') break;
                cout << "Answer is: " << ob.eval_exp(expstr) << "\n\n";
        }
        cout << endl;
        return 0;
    }
    Hope that helps

  8. #8
    Registered User
    Join Date
    Nov 2005
    Posts
    22
    thank you two.
    but i have a question about the same subject:
    1. if i put an integer number a char variable so the number will become a character(ASCII)?

  9. #9
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    Barnzey, this is the C forum. Not C++.

    1. if i put an integer number a char variable so the number will become a character(ASCII)?
    People tend to make this stuff too complex. It's really very simple. Characters are simply small integers. So to print a zero on the screen you can either do: putchar('0'); or putchar(48);

    So if you want to change a character representation of an integer (e.g. '5') you can just do: int num = '5' - '0';

    The reason functions like atoi() exist are because multidigit input (e.g. "53") is a bit trickier.

    So to finally answer your question, no, the type of variable makes no difference whatsoever. Doing char ch = 4; is not the same as doing char ch = '4';.
    Last edited by itsme86; 11-16-2005 at 12:02 PM.
    If you understand what you're doing, you're not learning anything.

  10. #10
    Registered User
    Join Date
    Nov 2005
    Posts
    22
    anyone can answer to my question?

  11. #11
    Registered User
    Join Date
    Oct 2005
    Posts
    38
    my bad, forgot that was a C++ source code. I've got a C version but its not on the PC, would mean typing it up. If i get time ill post it.

    Do you mean having somthing like:

    a = 5
    b = 6
    a+b =
    11

    so you input a = 5 and b = 6?

  12. #12
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Quote Originally Posted by snaidis
    anyone can answer to my question?
    Compile and run this.
    Code:
    #include <stdio.h>
    #include <ctype.h>
    
    int main(void)
    {
       int i;
       for ( i = 0; i < 128; ++i )
       {
          printf("i = %3d", i);
          if ( isprint(i) )
          {
             printf(" = '%c'", i);
          }
          if ( isdigit(i) )
          {
             printf(" (digit)");
          }
          if ( isalpha(i) )
          {
             printf(" (alpha)");
          }
          putchar('\n');
       }
       return 0;
    }
    Does that help you better rephrase your question?
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help with this compiler error
    By Evangeline in forum C Programming
    Replies: 7
    Last Post: 04-05-2008, 09:27 AM
  2. Stone Age Rumble
    By KONI in forum Contests Board
    Replies: 30
    Last Post: 04-02-2007, 09:53 PM
  3. Logical errors with seach function
    By Taka in forum C Programming
    Replies: 4
    Last Post: 09-18-2006, 05:20 AM
  4. about wide character and multiple byte character
    By George2 in forum C Programming
    Replies: 3
    Last Post: 05-22-2006, 08:11 PM
  5. If else works but I can't do it with switch
    By g1bber in forum C++ Programming
    Replies: 1
    Last Post: 04-19-2006, 07:02 PM