-
basic code help
Hey, I am new to programming and I was trying to make a basic add program. It is working fine until it asks you if you want to do it again and no matter if I push y or n it does nothing. What am I missing?
Code:
#include <iostream>
using namespace std;
int mult (int a, int b);
int main() //Trying to make a basic add program. After you add will ask if you want
{ //to do another problem but isn't. to try and simplize the program erased
int a; //code to make program repeat when you do again and simply put it works
int b; //until i can find out why if statement is not working.
char y, n;
cout<<"Please input the two numbers to be added: ";
cin>> a >> b;
cin.ignore();
cout<<" The sum of the two numbers is: "<< mult (a, b) <<"\n";
cin.get();
cout<<"Would you like to add again? (y/n): ";
cin>> y >> n;
cin.ignore();
if ( y == y ) {
cout<<"It works\n";
}
}
int mult (int a, int b)
{
return a + b;
}
-
Code:
int a = 0, b = 0;
char again = 'y'; // Well the user is only going to be making one choice
// so it needs just one variable
while(again != 'n') { // make sure you compare it to a character
cout<< "Please enter two digits to add: ";
cin>> a >>b;
cout<< "The sum is " <<add(a, b) <<endl;
cout<< "Got another problem? ";
cin>> again;
}
Something like that.
-
when you ask the user if they want to repeat, you only need to input into one char and check to see if that's 'y'. so get rid of the n variable, change cin >> y >> n; to cin >> y; and then your if statement, put single quotes around the second y so that it compares the contents of the y variable to the character y. if (y == 'y'). otherwise it checks to see if y is equal to itself, which will always be true.
-
>> if ( y == y )
should be
if ( y == 'y' )
-
citizen's code it a perfect candidate for a do-while loop.