-
C++ Beginner Help
I'd like to start by letting everyone know that I've been programming (or trying, at least) for only a couple weeks, therefore I know very little about vocabulary so please provide a definition for programming-specific words. I am currently reading the Beginner Tutorial guide on this website, also a few C++ books.
Alright, I only made it to the second section, If Statements, and I'm trying to make a quiz-like program. So here is my code:
Code:
#include <iostream>
using namespace std;
int main()
{
char A, B, C, D;
cout<<"What year was WWII thought to be started? ";
cout<<"A. 1931";
cout<<"B. 1945";
cout<<"C. 1939";
cout<<"D. 1967";
char>> A;
char>> B;
char>> C;
char>> D;
cin.ignore();
if (int = A){
cout<<"1931 is incorrect. C was the right answer.";
}
if (int = B){
cout<<"1945 is incorrect. C was the right answer.";
}
if (int = C){
cout<<"1939 is correct. Good job!";
}
if (int = D){
cout<<"1967 is incorrect. C was the right answer.";
}
cin.get();
}
Can somebody tell me where I went wrong? Now I'm not asking anybody to do this for me, but just give me a few hints on where I messed up. For the record, I'm using Dev-C++ 4.9.9.2
-
You're mixing chars and ints, and for the input you only need one char option:
Code:
char input;
cout<<"What year was WWII thought to be started? ";
cout<<"A. 1931";
cout<<"B. 1945";
cout<<"C. 1939";
cout<<"D. 1967";
cin >> input;
if (input == 'A' || input == 'a'){
Also, make sure that you use == when comparing two things. = on its own assigns the value on the right to the variable on the left. With the options you should use else if statements:
Code:
if (condition 1)
{
}
else
if (condition 2)
{
}
else
if (condition 3)
{
}
else
if (condition 4)
{
}
else
//code for none of the above...
And use either << endl or "\n" to move to the next line in your output.
-
For this part:
Code:
if (input == 'A' || input == 'a'){
Would I need to do this for every char I want to do? If so, it would look like this right?
Code:
if (input == 'A' || input == 'a'){
//code
else if (input == 'B' || input == 'b'){
//code
else if (input == 'C' || input == 'c'){
//code
else if (input == 'D' || input == 'd'){
//code
I got it I believe. One more question, how do you make these: "||"?
-
Yes that's right. When working with specific characters you enclose them in ' '. Later on there are ways to convert input to lower or upper case, but for now checking for either does the job.
|| means OR as far as C++ is concerned. As for where | lives on your keyboard....that depends on where you are. Here in the UK the symbol is on the backslash key next to 'Z'. It looks like one of these : that's been squished on the keyboard rather than |.
-
I found it |. Thanks for the help!