Not understanding my output result

I am suppose to making a program for class that if any D is entered lower or upper case, the program is suppose to return Dog to the screen. Any other letter will return Cat. I keep getting t as my result and I can not figure out as to why. This is one of my first programs in class using the if/else. Thanks for any help or ideas on how to get back on track is much appriciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>

using std::cout;
using std::cin;
using std::endl;

int main()
{    
    //declare variable
    char animal = ' ';
    int letter = 0;

    //enter input
    cout << "Enter Animal ID: ";
    cin >> animal;
    if (toupper(letter) == 'D')
    {
        letter = toupper(letter);
        animal = 'Dog';
    }
    else
    {
        animal = 'Cat';
    }
   

   
    //display output
    cout << animal << endl;


    return 0;
}    //end of main function 
char's store an individual character. animal = 'Cat'; <-- this is not doing what you expect.

if you want to store a string, use a std::string instead of a char:

1
2
3
4
5
6
7
8
#include <string>
using std::string;

//...
string animal;

//...
animal = "Cat";  // note the double quotes here, not single quotes 
Let me write out the whole statement for the program from my assignment. The reason is because I just want to make sure I explained it correctly the first time I am not thinking so.

The program should prompt the user to enter an animal ID, then store the users response in a char variable named animal. The program should display the string "Dog" when the animal variable contains the letter D (in any case); otherwise, it should display the string "Cat"
Your input is also faulty (logically), you do a cin on animal, but you're checking letter (which is an int by the way):

1
2
3
4
5
6
    char letter = 0;

    //enter input
    cout << "Enter Animal ID: ";
    cin >> letter;
    if (toupper(letter) == 'D')
the variable animal is a char.

@vwyodapink there are two types of text storage in C++, that are commonly used. Chars and strings. Chars are a single character, basically 0-255 in ASCII, go look it up if you don't know what ASCII is. Strings are a series of chars located next to each other in memory, with the last char being a '\0', always. Double quotes (" ") indicate that you want the stuff inside the quotes to be treated as a string, and single quotes (' ') indicate that you want it treated as a single char. Some if you write 'Cat' the compiler should return a compile times error, but I guess some will just store it as 't'. So you should go look up the Std::string library on this site, or on google.
Topic archived. No new replies allowed.