So my question is, why am I getting the wrong output at the end of run time?
I've been practicing my C++ coding and I wrote the following program, but for some reason I'm not getting the output that I want.
#include <iostream>
using namespace std;
int main()
{
int number;
int a;
int x = 'Yes';
int y = 'yes';
cout<<"Please enter a number: ";
cin>> number;
cin.get();
cout<<"You have entered: "<<number<<"\n""\n";
cout<< "Is this correct?""\n";
cin>> a;
if ( a == x ){
cout<<"Congratulations!!!";
}
else if ( a == y ){
cout<<"Congrats!!!";
}
else {
cout<<"Please Try Again.";
}
cin.get();
}
That ends the code, now, a quick note to keep in mind, on the output line : cin<< a; here we are suppose to get the input of the person, I'm expecting that the person inputs the word "yes", but there is a chance that the person might input "Yes" instead, with a Capital Y.
That's why I have the If Statement. The problem is that when I run the Program, no matter what i input, I always get "Please Try Again" instead of Congratulations.
ints are for integers.
If you want to store text, you need to use a string variable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <string>
#include <cctype>
int main()
{
int number;
std::cout << "Please enter a number: ";
std::cin >> number;
std::cout << "You have entered " << number << ".\n\n";
std::cout << "Is this correct? ";
std::string response;
std::cin >> response;
if (response == "yes" || response == "Yes")
std::cout << "Congratulations!";
else
std::cout << "Please try again.";
}
In practice, I would just convert all of the characters to lowercase (using std::tolower, in the <cctype> header) and then just check for if (response == "yes").
OOHH ok, that makes sense, so I have to declare strings not integers got it. Your codes looks clean, short, and it's easier to read. Thank you very much for your help.