Thread: How can I define something a character AND an integer in the same time?

  1. #1
    Registered User
    Join Date
    Jul 2002
    Posts
    15

    How can I define something a character AND an integer in the same time?

    How can I define something a character AND an integer in the same time? So that the user may type a letter or a number?
    also for the ifs afterwards, will this work?

    for characters:

    Code:
    if(input=='a')
    for numbers

    Code:
    if(input=9)
    Thanks in advance.
    "Nobility is not a birtright, but is defined by someone's actions." Robin Hood

  2. #2
    Registered User
    Join Date
    Jul 2002
    Posts
    16
    You can't. A variable can only be one single type.

    However, the numbers 0 through 9 still are characters, as well, so typing in a number would work with a character variable.

  3. #3
    Mayor of Awesometown Govtcheez's Avatar
    Join Date
    Aug 2001
    Location
    MI
    Posts
    8,823
    Just call it a char.

    if (input == 'a')

    if (input == '9')


    Same deal.

  4. #4
    Registered User
    Join Date
    Jul 2002
    Posts
    15

    Thanks but...

    Thanks guys!!!
    But what if I need to use something higher than 9 or lower than 0, will it be impossible?
    "Nobility is not a birtright, but is defined by someone's actions." Robin Hood

  5. #5
    Registered User
    Join Date
    Nov 2001
    Posts
    1,348
    You should use a structure or a class containing the two different variable types. Ultimately, a character is not an integer and an integer is not a character.

    Kuphryn

  6. #6
    Registered User
    Join Date
    Jul 2002
    Posts
    16
    Well, not necessarily, you could do this for numbers out of that range:

    Code:
    #include <iostream.h>
    #include <stdlib.h>
    #include <ctype.h>
    
    int main()
    {
    
        char input[10];
        int intInput;
    
        cin.getline(input, 10);
    
        // checks to see if the first character is a number
        if (isdigit(input[0])
          intInput = atoi(input);  // changes the string of digit characters (if that's what it is)
                                   // to an integer
    
    }
    That will make it so that if the person enters a number, the program will convert the characters into an integer and assign its value to "intInput".
    Last edited by Gabu; 07-22-2002 at 11:01 AM.

  7. #7
    Registered User
    Join Date
    Jul 2002
    Posts
    15

    Thanks!

    Thanks all, I really get the best answers here, keep the good work guys!
    "Nobility is not a birtright, but is defined by someone's actions." Robin Hood

  8. #8
    Green Member Cshot's Avatar
    Join Date
    Jun 2002
    Posts
    892
    Perhaps you should declare a union? Maybe not the best way to go about it though.

Popular pages Recent additions subscribe to a feed