In exercise ten of chapter 3 in this book im trying to go over, I was asked to write a program that takes an operation followed by two operands and output the results.
Read the operation into a string called operations and use an if-statement to figure out which operation the user wants.Read the operands into variables of type double. Implement this for operations called +,-,*,/, you know (plus, minus, multiplication, division) the obvious.
This is what I wrote so far and it worked and all but my issues is the concept of the condition in the if-statements. From what I understand the if statement has parenthesis, that within are the conditions where the values are tested to see if they are true or false, Only after that the computer decided whether to run the code or not. So tell me why do I have to write the operation equal to the operator as the conditions, when I have to use the operator in the cout to get the results of the two input values anyway ? I don't understand this, isn't there a better way of writing this with less statements ?
#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;
int main()
{
string operation = "";
double operands1;
double operands2;
cout << "Give me either a minus, plus, division, or multiplication operations \n";
cin >> operation;
cout << " enter the value you would like to \n";
cin >> operands1;
cout << " enter the second value you would like to \n";
cin >> operands2;
if (operation == "+")// I was told to write it like this in the book {
cout << operands1 + operands2 << endl;
}
else if (operation == "*") {
cout << operands1*operands2 << endl;
}
else if (operation == "-") {
cout << operands1 - operands2 << endl;
}
else if (operation == "/") {
cout << operands1 / operands2 << endl;
}
else {
cout << " seriously dude im talking about numbers over here \n";
}
return 0;
}
For single character operations you can use a switch statement :
switch (c) {
case '+' : std::cout << op1 + op2 << std::endl; break;
case '*' : ...
...
default : std::cout << "my dud!" << std::endl;
}
If you care about number of statements, you could also use an ugly ternary operator:
std::cout << (c=="+" ? op1+op2 : c=="*" ? op1*op2 : "DUDEEE!") << std::endl;
If you're asking why you can't do something like this:
cout << operands1 operation operands2 << endl;
It's because that's not how the language is structured. You can't put a variable in a place where an operator would be and expect it to be substituted in. Suppose operation didn't contain an operand. What would happen then?
What you have now is the simplest way of handling this.
The assignment is somewhat confusing because the operator "+" is actually a string.
if (operation == "+")// I was told to write it like this in the book {
cout << operands1 + operands2 << endl;
}
The variable operation is a variable that holds letters and words. We call this type of variable a string variable. This is confusing to the least.
The if statement then asks whether the word contained in the variable operation is equal to the string "+". This is more confusing because we usually see a plus-sign as a symbol. In your program, the plus-sign "+" is a string.
So, the conditional in the parenthesis is asking if the operation string contains the string "+". If it does, then the code following that will be executed.
The + in the next line is now a real addition symbol, which will add the values in the two operands for printing.
Related
I'm trying to create a small restaurant program in which I'll be practicing everything I learned in C++ so far. However I jumped into a small issue. At the beginning of the program, I prompt the user whether they want to enter the program, or leave it by choosing Y or N. If the input is anything other than that the program will tell the user is invalid.
The issue is lets say the user input one invalid character a.
The invalid output will be displayed normally and everything seems perfect.
But if the user inputs two characters, or more, the invalid output case will be printed as many as the characters input by the user. Sample below:
Output image
#include <iostream>
int main()
{
char ContinueAnswer;
std::string Employee {"Lara"};
std::cout << "\n\t\t\t---------------------------------------"
<< "\n\t\t\t| |"
<< "\n\t\t\t| Welcome to OP |"
<< "\n\t\t\t|Home to the best fast food in Orlando|"
<< "\n\t\t\t| |"
<< "\n\t\t\t--------------------------------------|" << std::endl;
do
{
std::cout << "\n\t\t\t Would you like to enter? (Y/N)"
<< "\n\t\t\t "; std::cin >> ContinueAnswer;
if(ContinueAnswer == 'y' || ContinueAnswer == 'Y')
{
system("cls");
std::cout << "\n\t\t\t My name is " << Employee << "."
<< "\n\t\t\tI will assist you as we go through the menu." << std::endl;
}
else if(ContinueAnswer == 'n' || ContinueAnswer == 'N')
{
std::cout << "\t\t\t\tGoodbye and come again!" << std::endl;
return 0;
}
else
std::cout << "\n\t\t\t\t Invalid Response" << std::endl;
}
while(ContinueAnswer != 'y' && ContinueAnswer != 'Y')
Thank you for taking time to read and for anyone who answers :)
You could simply make the user input a string:
std::string ContinueAnswer;
and compare like this:
if(ContinueAnswer == "y" || ContinueAnswer == "Y")
which will handle multi-character inputs.
If you want to handle spaces in the input as well, change the:
std::cin >> ContinueAnswer;
to:
std::getline(std::cin, ContinueAnswer);
Before addressing your question I need to point out that you should always verify that the input was successful before doing anything with it. Processing variables which were not set due to the inout failing is a rather common source of errors. For example:
if (std::cin >> ContinueAnswer) {
// do something with successfully read data
}
else {
// deal with the input failing, e.g., bail out
}
I assume you consider everything on the same line to be invalid if nine of the expected characters was read. You could read a line into an std::string. However, that could be abused to provide an extremely long line of input which would eventually crash your program. Also, reading data into a std::string just to throw it away seems ill-advised. I’d recommend ignoring all characters up to and including a newline which could be done using (you need to include <limits> for this approach):
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), ‘\n’);
The first argument is a special value indicating that there may be an arbitrary amount of character before the newline. In practice you could probably use a value like 1000 and it would be fine but it can be gamed. Of course, in a real application a dedicated limit may be used to prevent an adversary to keep the program busy for long. I tend to assume my programs are under attack to make sure I deal with unusual cases.
A quick refactor produces this:
#include <iostream>
#include <cstring>
#include <stdio.h>
int main()
{
char ContinueAnswer[256];
std::string Employee {"Lara"};
std::cout << "\n\t\t\t---------------------------------------"
<< "\n\t\t\t| |"
<< "\n\t\t\t| Welcome to OP |"
<< "\n\t\t\t|Home to the best fast food in Orlando|"
<< "\n\t\t\t| |"
<< "\n\t\t\t--------------------------------------|" << std::endl;
do
{
std::cout << "\n\t\t\t Would you like to enter? (Y/N)"
<< "\n\t\t\t "; std::cin.getline(ContinueAnswer,sizeof(ContinueAnswer));
if(strcmp(ContinueAnswer, "Y") == 0 || strcmp(ContinueAnswer, "y") == 0)
{
system("cls");
std::cout << "\n\t\t\t My name is " << Employee << "."
<< "\n\t\t\tI will assist you as we go through the menu." << std::endl;
}
else if(strcmp(ContinueAnswer, "N") == 0 || strcmp(ContinueAnswer, "n") == 0)
{
std::cout << "\t\t\t\tGoodbye and come again!" << std::endl;
return 0;
}
else
std::cout << "\n\t\t\t\t Invalid Response" << std::endl;
}
while(true);
}
The cin.getline will get all characters until a delimiter. Then, you can check for equivalence using strcmp and reject anything other than what you want. Lastly, it seems like you are wanting this to be in an infinite loop, so don't worry about checking the input at the end and just loop back.
I'm very new to C++, just started learning using an online course about 30 minutes ago. I'm a little confused as to why this string comparison isn't working in a basic math script:
#include <iostream>
#include <string>
using namespace std;
int main() {
int one, two, answer;
char *oper;
cout << "Add two numbers\n\nEnter your first number" << endl;
cin >> one;
cout << "Choose an operator: + - * / %%" << endl;
cin >> oper;
cout << "Enter your second number" << endl;
cin >> two;
if (oper == "+") {
answer = one + two;
}
else if (oper == "-") {
answer = one - two;
}
else if (oper == "*") {
answer = one * two;
}
else if (oper == "/") {
answer = one / two;
}
else if (oper == "%%") {
answer = one % two;
}
cout << one << " " << oper << " " << two << " = " << answer << endl;
return 0;
}
The values for one, oper, and two are 1, "+", and 1 respectively, but in the end, 1 + 1 = 4201435 is printed out. None of the if/else if statements are being executed. What's causing this?
You're comparing char * using operator==. Either let oper be a std::string instead
std::string oper
To use the string comparison listed here: http://en.cppreference.com/w/cpp/string/basic_string/operator_cmp
or if you need to use a char * for some restriction, use strcmp:
if (!strcmp(oper, "+")) {
// ...
You also need to have your operand variable point at some buffer too, for the stream to read into. This is a little bit more complicated and I just recommend changing the type of oper to std::string.
The problem with the code you have is that it's comparing pointers to char arrays. What you get from your input methods is going to be a new string from the input stream and will never have the same address as the readonly strings in your program.
So since none of the condition is true, ans hasn't been assigned. So output it accounts for an undefined behavior.
The value starts from 0 and can then be calculated using any operand of Mathematics. The code compiles successfully but doesn't work. The terminal windows shows 'Abort', 'Retry' and 'Cancel'. The rule is that you cannot use 2 operands but just keep adding the previous number to present operand.
#include <iostream>
#include <cmath>
using namespace std;
void Input(double input);
int main()
{
double sign, input;
cout << "This program calculates any given number upto 1 decimal place using the following operators:" << endl;
cout << " '+' - Addition." << endl;
cout << " '-' - Subtraction" << endl;
cout << " '*' - Multiplication." << endl;
cout << " '^' - Root." << endl;
cout << " '/' - Division." << endl;
Input(input);
return 0;
}
void Input(double IN)
{
char q;
char sign;
int Val = 0.0;
cin >> sign >> IN;
while (IN != q)
{
if (sign = '-')
Val -= IN;
if (sign = '+')
Val += IN;
if (sign = '*')
Val *= IN;
if (sign = '/')
Val /= IN;
cout << endl << "Result so far is " << IN;
IN++;
}
}
Your main problem is
q is undefined so the while(IN != q) will become undefined behavior
in C++, for any primitive datatype = means assignment operator, and not a comparator operator. To compare something use == instead.
Val is a variable with int datatype but assigned with value 0.0 which is a float or double.
What your program do in the if statement is : (for example this if statement)
if (sign = '-')
The program assign the value of - which is 45 to the sign variable
The if statement check the variable sign for value 0
if the value is 0 then the statement considered false and the block is skipped
if the value is other than 0 then the statement considered true and enter the block
The program run the code inside the if block
The program do all of those 3 thing for every if statement in your code, and I rarely run my own code in Windows so I can't very sure why the program giving the Run-Time Check Failure #3-T error
A little advice, use switch whenever you need to use multiple if statement, since it is easier to read.
Alright guys so I'm learning C++ using Bjarne Stroustrup's Programming Principles and Practice Using C++ book, and one of the drills asks me to
Step one: Enter a number followed by a unit(allow cm, m, in, and ft)
Step two: Convert that number into meters and output it
Step three: Reject any unit that the program doesn't know how to convert
Step four: Reject any values without units
Here is what I have so far:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
inline void keep_window_open() { char ch; cin>>ch; }
int main()
{
constexpr double cm_to_m = 100;
constexpr double cm_to_in = 2.54;
constexpr double in_to_ft = 12;
double i, in_meters;
string unit;
while (cin >> i)
{
cin >> unit;
if(unit == "cm" || unit == " cm") {in_meters = i / cm_to_m; cout << "That is " << in_meters << "m" << endl;}
else if(unit == "in" || unit == " in") {in_meters = i * cm_to_in / cm_to_m; cout << "That is " << in_meters << "m" << endl;}
else if(unit == "ft" || unit == " ft") {in_meters = (i * in_to_ft) * cm_to_in / cm_to_m; cout << "That is " << in_meters << "m" << endl;}
else if(unit == "m" || unit == " m") {cout << "That is " << i << "m" << endl;}
else if() cout << "You need to enter a unit after the number(cm, m, in, ft)" << endl;
else cout << "I don't know that unit" << endl;
}
}
My problem is at step four. I cannot, for the life of me, figure out how to check if no unit has been entered after the number. I've tried if(unit == " "), and everything similar to that, but when I just type in a number, it continues until I type in a unit.
If you guys can help with just giving hints so I can figure it out myself, that would be helpful :)
TIA
I think you could wait till there is a \n(end of line) and check if there is no unit
First off, you should always check whether input is successful after an attempt to read it. To do so, you'd check the stream state. Typically, that's done in combination with the read, e.g.:
if (std::cin >> unit) {
// ...
}
else {
// deal with no input being received
}
From the looks of it you want to constrain where the unit is located relative to the previous value: it seems you want the unit to be directly adjacent to the value or separated with at most one space. The input operator for std::string, like all well-behaved input operators, starts with skipping leading whitespace by default. If you don't want to allow arbitrary whitespace, you'll need to test for that explicitly.
When you want to allow at most one space character, you would need to deal with that explicitly. To do so you'd peek() at the next character and if it is a space (' ') you'd ignore() it. Next you can either disable skipping of leading whitespace using std::noskipws or peek() at the next character and fail if it is a whitespace character (std::isspace()). The next step would be reading the unit.
That is, reading the unit immediately after the value could look like this:
if (std::cin.peek() == ' ') {
std::cin.ignore();
}
if (std:cin >> std::noskipws >> unit >> std::skipws) {
// see if unit is a valid unit
}
else {
// no unit was entered where expected
}
The unit variable won't include a space character unless you read the string differently, e.g., using std::getline(). Thus, you can simply check the unit against "cm", "in", etc. There is no point to check it against " cm" for example as this test will always fail.
In addition I'd also get rid of the if () in your code: it serves no purpose other than adding confusion. I'm not even sure whether it is legal. gcc and clang both refuse to compile code containing an if-statement with an empty condition.
Finally, instead of keep_window_open() I'd just wait for some input using std::cin.ignore();. If you insist in keeping this function, its implementation could still be simplified to become std::cin.ignore();.
Sorry if it's something simple, but I'm new to C++ and haven't really gotten a good hold on it, yet. I need to build a calculator whose only named variables are pointers, and this is what I have so far, but I keep getting errors and I can't figure out why. Every error that always related to my if construct, though.
int main()
{
//Creating variables
//Values to perform operations on
float *aptr = new(nothrow)float;
float *bptr = new(nothrow)float;
float *ansptr = new(nothrow)float;
int *endptr = new(nothrow)int;
char *operationptr = new(nothrow)char;
cout << "Simple Operation Calculator" << endl; //Displays program name
cout << "Performs +, -, *, or / on any two real operands." << endl; //Describes nature of program to user
*endptr = 1;
while(*endptr = 1) //Creates a loop so that the user may perform as many operations as desired
{
//Prompts the user for the first operand
cout << "First operand: " << endl;
cin >> *aptr;
//Prompts user for operator
cout << "Operator(+,-,*,/): " << endl;
cin >> *operationptr;
//Prompts user for second operand
cout << "Second operand: " << endl;
cin >> *bptr;
//Performs requested operation
if(*operationptr == '+' || *operationptr == 'plus')
{
*ansptr = *aptr + *bptr;
}
else if(*operationptr == '-' || *operationptr == 'minus')
{
*ansptr = *aptr - *bptr;
}
else if(*operationptr == '*' || *operationptr == 'times')
{
*ansptr = *aptr * *bptr;
}
else if(*operationptr == '/' || *operationptr == 'divided by')
{
if(*bptr = 0)
{
cout << "Cannot divide by zero. Terminating program." << endl;
*endptr = 2;
break;
}
*ansptr = *aptr / *bptr;
}
else
{
cout << "Invalid operand input. Terminating program." << endl;
*endptr = 2;
break;
}
//Displays results
cout << *aptr << *operationptr << *bptr << " = " << *ansptr << endl;
//Asks user if they wish to perform another operation. If so, they stay in loop. If not, then break from loop.
cout << "Do you wish to perform another operation? (1 = yes, 2 = no)" << endl;
cin >> *endptr;
//If 1, loop repeats. If 2, program ends.
if (*endptr == 2)
{
cout << "Thank you for using my program. Goodbye!" << endl;
}
} //end while loop
return 0;
}//end main function
There are character literals (with ') and string literals (with "). Character literals have one character. String literals are arrays of characters. You can't write something like 'plus' because it has more than one character (well technically you can, but it's a multi-character literal, but lets not go there).
Nonetheless, this wouldn't make any sense because operationptr points at a single char object. A single char can't contain the entire word plus.
If you want to be able to accept plus as input, then I suggest you start using strings. In fact, use std::string.
As a side note, you are using pointers and dynamic allocation far too often. You are also forgetting to delete the objects that you create with new - this is a memory leak. I imagine you have come from a language that uses new for all object creation. In C++, this is not necessary (and is not a good practice). Instead, you can declare objects like so:
float aptr;
There is no need to dereference this object. You can just use aptr directly as a float.
'plus'
is a character constant, and can't contain more than one character.
'+' is fine, since it's a single character in a constant.
As per the comment on this answer,
'plus' could be ok, if the compiler is not expecting a char.