I am doing a programming exercise for my beginner class. The exercise is to write a c++ program that mimics a calculator.
This is the beginning of my code (not the entire code, just the beginning):
#include <iostream>
#include <string>
using namespace std;
int num1;
int num2;
double answer;
string op;
int main(void)
{
// Write your main here
cout << "Enter a number" << endl;
cin >> num1;
//Prompt user to enter an operator
cout << "Enter an operator (+, -, *, or /)" << endl;
cin >> op;
//Prompt user to enter another number
cout << "Enter another number" << endl;
cin >> num2;
//Determine whether or not addition was selected
if (op == "+")
answer = (num1 + num2);
cout << answer;
else
Regardless of what statements I put after that "else" statement, I am getting an error message that reads "Illegal else without matching if."
BUT, if I remove the preceding "cout << answer;" line, then the program compiles and runs fine.
What am I doing wrong?
Always use scope { ... } with if statements and for/while loops.
The problem is, if you don't use scope, then your if only encompasses the next statement underneath it (answer = (...). Because of this, the cout statement will happen ALL THE TIME, and the else isn't associated with the if statement. If you always use scope, you never have to worry about this.
if (op == "+") {
answer = (num1 + num2);
cout << answer;
}
You need to use {} braces on your if statement in order to execute multiple statements:
//Determine whether or not addition was selected
if (op == "+")
{
answer = (num1 + num2);
cout << answer;
}
else
...
You need to add the {} brackets between if and else because you have more than one statement.
This is what the compiler understands from your code:
if (op == "+")
answer = (num1 + num2);
cout << answer;
else
What you should do:
if (op == "+") {
answer = (num1 + num2);
cout << answer;
}
else
Related
enter image description hereI wrote C++ program which asks the user for two numbers and operator and gives the output based on the input.I think everything is correct but the output is not the desired output.
#include <iostream>
using namespace std;
int main()
{
int num1;
string op;
int num2;
string result;
cout << "Enter a number: ";
cin >> num1;
cout << "Enter a operator: ";
cin >> op;
cout << "Enter another number: ";
cin >> num2;
if (op == "+"){ //if user types '+' the result is num1 + num2
result = num1 + num2;
//cout << result;
}else if (op == "-"){ //if user types '-' the result is num1 - num2
result = num1 - num2;
// cout << result;
}else if (op == "*"){ //if user types '*' the result is num1 * num2
result = num1 * num2;
//cout << result;
}else if (op == "/"){ //if user types '/' the result is num1 / num2
result = num1 / num2;
//cout << result;
}else{
cout << "Invalid operator...";
}
cout << result;
return 0;
}
The output should be integer.But the output is just a diamond.
Declare the variable result as having the type int
int result = 0;
Or maybe it is even better to declare it as
long long int result = 0;
and use it like
result = static_cast<long long int>( num1 ) * num2;
In your program it has the type std::string
string result;
You are assigning a integer value to a string so I think so it is converting that integer value to character value and giving that emojis. My case was same as your, I
was assigning integer value to a string. But I then declared that integer value as a character value and it worked fine then.
Also the best approach is to use to_string() function to change the integer value to a character value.
I have to write a program in C++ and am unsure on how to return to the top after an error. For example, I have the user input 2 integers, if the 2nd integer is smaller than the first i have an error stating pls enter in a number larger than the first, but from here I do not know what code to enter to have the question be asked again / send to the beginning / top of the code?
if (num1 > num2)
cout << "You second number must be larger than your first number." << endl;
Problem
I do not know what code to enter to have the question be asked again / send to the beginning / top of the code?
Well almost always when you have that situation, you will use a while loop. This loops over the block if the condition is true.
#include <iostream>
#include <string>
int main()
{
int num1;
int num2;
do {
std::cout << "What is first num? ";
std::cin >> num1;
std::cout << "What is second num? ";
std::cin >> num2;
} while (num1 < num2);
}
Basically, what happens is first you have to declare the integers num1 and num2. Then you have a do while loop! Well this executes the code in the do block before checking for the condition! First we ask for the two user inputs, then we check for the condition. Let's look at the condition carefully:
while(num1<num2)
This means if the first number the user entered is less than the second number, loop through the while block. The while block does the same thing until num1 becomes greater than num2!
Here is a compiled version (GCC).
Additional Exercises
icodecool
Tutorial
CS_PDF
References
cpprefrence
MSDN
Flow Control Tutorial
Glossary:
do-while loop:
Executes a statement repeatedly until the value of the expression becomes false. The test takes place after each iteration.
Syntax
attr(optional) do statement while ( expression ) ;
attr(C++11) - any number of attributes
expression - any expression which is contextually convertible to bool. This expression is evaluated after each iteration, and if it yields false, the loop is exited.
statement - any statement, typically a compound statement, which is the body of the loop
Try:
cout << "Enter number 2: ";
cin >> num2;
while (num1 > num2) {
cout << "You second number must be larger than your first number." << endl;
cout << "Enter number 2: ";
cin >> num2;
}
int num1 = 0, num2 = 0;
do
{
cout << "num1: ";
cin >> num1;
cout << "num2: ";
cin >> num2;
if(num2 < num1)
cout << "error num2 is smaler than num1" << endl;
}while(num2 < num1);
I'm trying to code a postfix calculator, but I keep running into two issues-
first: When the calculator encounters a space, it sort of just exits immediately
second: when it encounters a non operator/non digit (ie- z) it doesn't display the error message that I coded.
int main()
{
stack <int> calcStack;
string exp;
char ans;
cout << "\nDo you want to use the calculator?" << endl;
cin >> ans;
while (ans == 'y')
{
cout << "\nEnter your exp" << endl;
cin >> exp;
for (int i = 0; i < exp.size(); i++)
{
if (isspace(exp[i]))
{
}
else if (isdigit(exp[i]))
{
int num = exp[i] - '0';
calcStack.push(num);
}
else
doOp(exp[i], calcStack);
}
while (!calcStack.empty())
{
calcStack.pop();
}
cout << "\nDo you want to use the calculator again?" << endl;
cin >> ans;
}
system("pause");
return 0;
}
This is the function--
void doOp(const char & e, stack <int>& myS)
{
if (myS.size() == 2)
{
int num1, num2, answ;
num2 = myS.top();
myS.pop();
num1 = myS.top();
myS.pop();
if (e == '+')
answ = num1 + num2;
else if (e == '-')
answ = num1 - num2;
else if (e == '*')
answ = num1 * num2;
else if (e == '/')
answ = num1 / num2;
else if (e == '%')
answ = num1 % num2;
else
cout << "\nError- Invalid operator" << endl;
cout << "\nCalculating..." << endl << answ << endl;
myS.push(answ);
}
else
cout << "\nInvalid stack size- too few, or too many" << endl;
}
In your main loop, you're reading strings with the string extractor:
cin >> exp;
THe string extractor is space sensitive. So as soon as a space char is encountered in the input, the string reading stops, and the witespace is not included in exp.
If you want to get a full line including spaces, you should opt for:
getline (cin, exp);
Edit:
The issue you experience with getline() is realted to the char extraction when you ask if user wants to use the calculator. Entering y is not sufficient. So you'l enter yenter. Only the y will be put into ans, so that getline() will start reading an empty line.
To solve this, update your initial input:
cin >> ans; // as before
cin.ignore (INT_MAX, '\n'); // add this to skip everything until newline included
Here an online demo showing that it works (including error message in case of wrong operator)
I got an assignment where we make a cmd prompt show up and display a flashcard game for multiplication. After inputting a correct answer a prompt shows up and asks the user to go "Again? Y/N." after the second input answer the prompt to ask the user doesn't show up and it's stuck on a "congratulations" message. This happens when I write in code to randomly generate two numbers for the game twice. one outside the while loop, and one inside while loop. If I leave one out the 2nd code for the random numbers it will run fine but will only display the same numbers over again. what I'm asking is how do I fix it so that it won't get stuck after the second answer input?
sample code below:
#include <iostream>
using namespace std;
int main()
{
int num1, num2, ans, guess, count = 0;
char choice;
num1 = rand() % 12 + 1;
num2 = rand() % 12 + 1;
//first number generator.
ans = num1 * num2;
do
{
{
cout << num1 << " X " << num2 << " = ";
cin >> guess;
cout << "Wow~! Congratulations~! ";
count++;
num1 = rand() % 12 + 1;
num2 = rand() % 12 + 1;
//second number generator.
} while (guess != ans);
cout << "\nAgain? Y/N: ";
cin >> choice;
} while ((choice == 'y') || (choice == 'Y'));
//after two turns the loop stops. Can't make a choice.
cout << " Thanks for playing! Number of tries:" << count << endl;
return 0;
}
I'd guess the problem is because your loops aren't quite what you think they are.
do
{
The code above has started a do loop.
{
I suspect you intended to start another (nested) do loop here--but you left off the do, so it's just a block that gets entered, executed, and exited. Useless and pointless in this case.
cout << num1 << " X " << num2 << " = ";
cin >> guess;
cout << "Wow~! Congratulations~! ";
count++;
num1 = rand() % 12 + 1;
num2 = rand() % 12 + 1;
//second number generator.
} while (guess != ans);
You've formatted this as if the while were closing the nested do loop--but since you didn't actually create a nested do loop, this is just a while loop with an empty body. Its meaning would be more apparent with a little re-formatting:
// second number generator
}
while (guess != ans)
/* do nothing */
;
The problem can be found here:
do
{
{
cout << num1 << " X " << num2 << " = ";
cin >> guess;
As you can see, the second scope has no do statement. As a result it is only a codeblock.
You can solve it by writing a do statement for the second code block.
Because the do is not present in the second bracket ({), the while is interpreted as a while loop:
while (guess != ans);
or
while (guess != ans) {
}
this thus keeps looping until guess is not equal to ans. But since in the loop does not modify any of the two variables, the loop will keep iterating.
Other errors: note that the program is still incorrect, since it will claim you have answered the question, regardless of the answer. You can fix it by implementing this as follows:
int main()
{
int num1, num2, ans, guess, count = 0;
char choice;
do {
num1 = rand() % 12 + 1;
num2 = rand() % 12 + 1;
ans = num1 * num2;
do {
cout << num1 << " X " << num2 << " = ";
cin >> guess;
if(guess == ans) {
cout << "Wow~! Congratulations~! ";
} else {
cout << "No, wrong!\n";
}
count++;
} while (guess != ans);
cout << "\nAgain? Y/N: ";
cin >> choice;
} while ((choice == 'y') || (choice == 'Y'));
//after two turns the loop stops. Can't make a choice.
cout << " Thanks for playing! Number of tries:" << count << endl;
return 0;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Made my first C++ program ever. A basic calculator.
Got stuck at this part where I was suppose to make the program repeat.
So at "Point A" you select if you want to count division/addition etc. and it takes you there. When you run it once, it asks if you want to repeat the function (e.g division) or go back to the "Point A" (you just type y[yes] (repeats the division) or n[no](goes to "point A")).
I'm new to C++, haven't got really familiar with loops yet.
Also the code structures make my head spin, so Google didn't help me much.
I've heard about the "goto" function (or whatever you call it) but I was told that i shouldn't be used in this case.
Take a look. The texts, and most of the comments are in Finnish, but I hope you'll get the point from English comments.
#include <iostream>
using namespace std;
float addition(float num1, float num2)
{
return num1 + num2;
}
float substraction(float num1, float num2)
{
return num1 - num2;
}
float multiplication(float num1, float num2)
{
return num1 * num2;
}
float division(float num1, float num2)
{
return num1 / num2;
}
//This function should throw you back to point 'A'
int valinta2{
while (valinta2 == y){
}
}
int main(void)
{
//Point A
float number1;
float number2;
int valinta;
cout << "\n-*-*-*-*-*-*-*-*-*-*\nClaudion Laskin\n-*-*-*-*-*-*-*-*-*-*";
//Select what you want to count
cout << "\n\n\nValitse mita haluat laskea. \n\nVaihtoehdot: " << endl;
cout << "1. Plus-laskut\n 2. Vahennys-laskut\n 3. Kerto-laskut\n 4. Jako-laskut \n\nValinta: ";
cin >> valinta;
if (valinta == 1){
//Addition
cout << "\n\n\n===============\n||Plus laskut||\n=============== \n\nSyota ensimmainen numero: ";
cin >> number1;
cout << "\n\n+\n\nSyota toinen numero: ";
cin >> number2;
cout << "\nTulos: " << addition(number1, number2) << "\n----------\n" << endl;
cin.get();
//if 'y' run the task again, if 'n' goto start
cout << "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\nKirjoita 'y' jos haluat jatkaa, 'n' jos haluat valikkoon\n-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n";
cin.get();
}
else {
if (valinta == 2){
//Subtraction
cout << "\n\n\n===================\n||Vahennys laskut||\n=================== \n\nSyota ensimmainen numero: ";
cin >> number1;
cout << "\n\n-\n\nSyota toinen numero: ";
cin >> number2;
cout << "\nTulos: " << substraction(number1, number2) << "\n----------\n" << endl;
cin.get();
//if 'y' run the task again, if 'n' goto start
cout << "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\nKirjoita 'y' jos haluat jatkaa, 'n' jos haluat valikkoon\n-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n";
cout << "Valinta: ";
cin >> valinta2;
}
else {
if (valinta == 3){
//Multiplication
cout << "\n\n\n================\n||Kerto laskut||\n================ \n\nSyota ensimmainen numero: ";
cin >> number1;
cout << "\n\n*\n\nSyota toinen numero: ";
cin >> number2;
cout << "\nTulos: " << multiplication(number1, number2) << "\n----------\n" << endl;
cin.get();
//if 'y' run the task again, if 'n' goto start
cout << "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\nKirjoita 'y' jos haluat jatkaa, 'n' jos haluat valikkoon\n-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n";
cin.get();
}
else {
if (valinta == 4){
//Division
cout << "\n\n\n===============\n||Jako laskut||\n=============== \n\nSyota ensimmainen numero: ";
cin >> number1;
cout << "\n\n/\n\nSyota toinen numero: ";
cin >> number2;
cout << "\nTulos: " << division(number1, number2) << "\n----------\n" << endl;
}
}
}
}
system("pause");
return 0;
}
You need to restructure your code to include the while loop in the main method. There would be ways to "go to" your "Point A", but they are messy and shouldn't be used (goto is the keyword here).
So at "Point A", insert
do {
float number1;
// ...
and then down at where you would like to call valinta2 (notice that you don't even call the function at the moment - I'm guessing it would have to be just before the call to system("pause")), do the check of the condition, like so:
} while (...);
And best revisit the chapter on flow control/loops in the C++ tutorial of your choice, e.g. one of those mentioned here: The Definitive C++ Book Guide and List
Alternative to nyarlathotep's perfectly good answer, one method I like using follows this form:
while(true) {
//do stuff
//then when ready to check for exit condition
if(exitCondition == true) { //the ==true part is redundant
break;
}
//do more stuff
//if you need to go to the beginning of the loop and
//skip any code following a point, do this:
if(skipRestOfLoopCondition) {
continue;
}
//you can always check other exit conditions or check
//the same one at multiple places
if(someOtherExitCondition) {
break;
}
//do even more stuff
}
system("pause");
return 0;
As a caveat, you must provide a way for at least one of the if's that result in break; to actually execute, because while(true) loop condition never gets you out of the loop, you can only get out of the loop with a break;.
I am pretty new to this and I don't know if I am right. I can hardly understand your code. However, when I am programming in c for the arduino and I want my code to loop forever I just put
void loop() {// my code follows from here