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.
Related
I am so close to solving this roman numeral to integer problem. However, in my if statement for when character equals M, I am getting an error thrown when declaring my previous variable when the input is MCMXCIV for example. Because there is nothing before M, it is throwing an out-of-bounds error. How can I fix this?
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
using namespace std;
//Character to search and add to the integer
char character;
//The integer value that is needed to add up and output the corresponding value
int integer = 0;
//One of the test runs and what will be needed for every special case
int main()
{
//Roman numeral given
string input;
//Prompt for user to enter the roman numeral integer
cout << "Enter the roman numeral you want to convert into a number: " << endl;
cin >> input;
cout << input << " is what you are wanting to convert." << endl;
//Read through the string that is being inputted then assign values to the overall integer
for (int i = 0; i < input.length(); i++)
{
character = input.at(i);
cout << "This is the character that is being read right now: " << character << endl;
//Arithmitic for when the character is found and the corresponding value needs to be added
if(character == 'I')
{
integer+=1;
cout << "Integer value now: " << integer << endl;
}
else if(character == 'V')
{
char previous = input.at(i-1);
integer+=5;
if(character == 'V' && previous == 'I')
{
integer = integer - 2;
}
cout << "Integer value now: " << integer << endl;
}
else if(character == 'X')
{
integer+=10;
cout << "Integer value now: " << integer << endl;
}
else if(character == 'L')
{
integer+=50;
cout << "Integer value now: " << integer << endl;
}
else if(character == 'C')
{
integer+=100;
cout << "Integer value now: " << integer << endl;
}
else if(character == 'D')
{
integer+=500;
cout << "Integer value now: " << integer << endl;
}
else if(character == 'M')
{
char previous = input.at(i-1);
integer+=1000;
if(character == 'M' && previous == 'C')
{
integer -= 200;
}
cout << "Integer value now: " << integer << endl;
}
}
cout << "The integer value is: " << integer << endl;
}
First of all: Good that you used the at() function. So you could detect the "out of bounds" problem.
in char previous = input.at(i - 1);, variable "i" could be 0 and you then try to access array element "-1", which is of course out of bounds for your use case.
So, you need an additional check, if "i" greater then 0, before subtracting.
But in general, your approach is too complicated. You can make your life easier, by analyzing or reading, how roman numerals are defined. Look for example here. And please read especially about the "subtractive notation".
You already noticed that but, unfortunately, your implementation is not always following that rule. You made the check only for "M" and "V". But basically, you need to do that for all literals (except "I").
You can boil down this to the rule:
If a literal before a following literal is less, then use the subtrative form. Or, even better, you can read from right to left and finally say:
"If the current literal is less than the follwoing, then use the subtractive form."
And what is the subtractive form? We can simply add the negative number. Example, using number 94 which is "XCIV". We start summing up from the right:
Start. Begin from right. Initialize sum with rightmost value: Looking at 'V': sum = 5
Next: Read 'I'. Check, if this is less than the following literal 'V'. Yes, it is. So, use subtractive form. Add the negative. Now sum = sum + (-1), sum = 4
Now: Read 'C'. Check, if this is less than the following literal 'I'. No, it is not. So, simply add the positive value. Now sum = sum + 100, sum = 104
Next: Read 'X'. Check, if this is less than the following literal 'C' . Yes, it is. So, use subtractive form. Add the negative. Now sum = sum + (-10), sum = 94
So, this is now a very simply algorithm. We will convert a roman literal (one letter) to a integer and then build a sum with positive or negative values.
One of many many potential implementations could look like this:
#include <iostream>
#include <string>
int convert(char romanLiteral) {
switch (romanLiteral) {
case 'I':
return 1;
case 'V':
return 5;
case 'X':
return 10;
case 'L':
return 50;
case 'C':
return 100;
case 'D':
return 500;
case 'M':
return 1000;
default:
return 0;
}
}
int romanLiteralStringToInteger(const std::string& romanLiteralString) {
// Sanity check:
if (romanLiteralString.empty()) return 0;
// Get length of input string
int lengthOfRomanLiteralString = static_cast<int>(romanLiteralString.length());
// Initialize sum with rightmost value
int sum = convert(romanLiteralString[lengthOfRomanLiteralString-1]);
// Now iterate over the string form right to left
for (int i = lengthOfRomanLiteralString - 2; i >= 0; --i) {
// Check if this literal is less than the following
if (convert(romanLiteralString[i]) < convert(romanLiteralString[i+1]))
sum -= convert(romanLiteralString[i]);
else
sum += convert(romanLiteralString[i]);
}
return sum;
}
int main() {
std::string romanNumber = "XCIV";
std::cout << romanNumber << " --> " << romanLiteralStringToInteger(romanNumber) << '\n';
}
In C++ you would probably use associative containers like std::map or std::unordered_map for converting one literal to a number. And maybe a ternary operator, instead of an if.
Then the problem could be implemented like the following:
#include <iostream>
#include <string>
#include <unordered_map>
int romanLiteralStringToInteger(const std::string& romanLiteralString) {
if (romanLiteralString.empty()) return 0;
std::unordered_map<char, int> T = { { 'I' , 1 }, { 'V' , 5 }, { 'X' , 10 }, { 'L' , 50 }, { 'C' , 100 }, { 'D' , 500 }, { 'M' , 1000 } };
int sum = T[romanLiteralString.back()];
for (int i = romanLiteralString.length() - 2; i >= 0; --i)
sum += (T[romanLiteralString[i]] < T[romanLiteralString[i + 1]] ? -T[romanLiteralString[i]] : T[romanLiteralString[i]]);
return sum;
}
int main() {
std::string romanNumber = "XCIV";
std::cout << romanNumber << " --> " << romanLiteralStringToInteger(romanNumber) << '\n';
}
And the hardcore solution with a stateful lambda.
#include <iostream>
#include <string>
#include <unordered_map>
#include <numeric>
#include <iterator>
std::unordered_map<char, int> ARTI{{'I',1 },{'V',5 },{'X',10 },{'L',50 },{'C',100},{'D',500 },{'M',1000 }};
int main() {
std::string romanNumber = "XCIV";
std::cout << std::accumulate(std::next(romanNumber.rbegin()), romanNumber.rend(), ARTI[romanNumber.back()], [&, next = ARTI[romanNumber.back()]](const int s, const char c) mutable {
int sum = s + (ARTI[c] < next ? -ARTI[c] : ARTI[c]); next = ARTI[c]; return sum; });
}
Good afternoon everyone, I am new to recursion and am trying to create a program to take user input to build a math function. It works when doing simple things such as 3 + 4, but when trying something like (3 + 4) + 6 the main prints an empty string. The purpose of the program is to place nested numbers inside parenthesis to make them clear to read. I have tried following the code, but the recursion seems to be what i don't understand. Thanks for your time and help.
Code
#include <iostream>
#include <string>
using namespace std;
string buildEq(bool nested, string tab);
int main()
{
cout << "Welcome to the equation builder!" << endl << endl;
cout << "Each step can only have one operation between two numbers." << endl;
cout << "So the equation (3 + 4) + 6 would have one 'nested' operation." << endl << endl;
string equation = buildEq(false, "");
cout << endl << "The equation you have built is... " << equation << endl;
cout << endl << "Thanks for coming!" << endl;
return 0;
}
string buildEq(bool nested, string tab)
{
string equation;
string nesting;
cout << tab << "For this step, is there nesting? (y/n): ";
cin >> nesting;
if(nesting == "y")
{
nested = true;
tab += "\t";
buildEq(true, tab);
}
else
{
int number = 0;
int operation_count = 1;
while(number < 2)
{
if(nested == true)
{
equation += "(";
}
string num= "";
cout << tab << "What number would you like to enter: ";
cin >> num;
equation += num+= " ";
number++;
while(operation_count == 1)
{
string operation;
cout << tab << "What operation would you like to perform? (+, -, /, *): ";
cin >> operation;
equation += operation += " ";
operation_count++;
}
if(nested == true && number == 2)
{
equation += ")";
}
}
}
return equation;
}
Correct output
Welcome to the equation builder!
Each step can only have one operation between two numbers.
So the equation (3 + 4) + 6 would have one 'nested' operation.
For this step, is there nesting? (y/n): n
What number would you like to enter: 3
What operation would you like to perform? (+, -, /, *): +
What number would you like to enter: 4
The equation you have built is... 3 + 4
Thanks for coming!
Press <RETURN> to close this window...
Function results empty
Welcome to the equation builder!
Each step can only have one operation between two numbers.
So the equation (3 + 4) + 6 would have one 'nested' operation.
For this step, is there nesting? (y/n): y
For this step, is there nesting? (y/n): n
What number would you like to enter: 3
What operation would you like to perform? (+, -, /, *): +
What number would you like to enter: 4
The equation you have built is...
Thanks for coming!
Press <RETURN> to close this window...
(Probably an overkill, but I don't think that the question itself is an easy example for understanding recursions)
In order to understand the recursion part, we need to look at the general problem, and understand how we progress from one invocation to another (the recursive step), and what is our stopping point (the base case) . Your goal here is to create a valid equation, in order to do so, your input should follow certain guidelines. Specifically, in order to verify such a problem, you need to verify that each input is following a syntax which is called Context Free Grammar, denoted by the following rules (N stands for number or nested, O for operation, D for digit and $ for nothing):
N -> ( N ) O | D O
D -> 0-9
O -> + N | - N | * N | / N | $
There are two recursions here. In each stage we need to get a valid equation, and those rules make sure it stays like that.
The following code is creating a proper equation from the user.
Notice a few important notes -
I'm using std::stringstream, which is more efficient at creating strings and appending to the existing "string".
You should not over-use std::endl, since in addition to adding a line break, it also flushes to the stdout, which is expensive.
Using "Using namespace std;" isn't a good habit!
Look at how I pass the same stringstream, and each stage adds to this, in order to create the general string. If your code doesn't add to the "carried" value, it means that you are doing nothing in this recursive step.
The code:
#include <sstream>
#include <iostream>
#include <string>
#include <cctype>
#include <assert.h>
void get_num_or_nested(std::stringstream& eq);
void get_operation_or_stop(std::stringstream& eq);
bool is_number(const std::string& s)
{
int digit_count = 0;
for (const char& character : s)
{
if (std::isdigit(character))
{
++digit_count;
}
}
return !s.empty() && s.size() == digit_count;
}
bool is_operation(char c)
{
return (c == '+' || c == '-' || c == '*' || c == '/');
}
std::string get_input_from_user()
{
std::string input;
std::cin >> input;
return input;
}
void get_operation_or_stop(std::stringstream& eq)
{
std::cout << "Insert one of the following:\n";
std::cout << "An operation - [ + | - | * | / ]\n";
std::cout << "s for Stop" << std::endl;
std::string input = get_input_from_user();
if (input.size() == 1)
{
if (is_operation(input[0]))
{
eq << input;
get_num_or_nested(eq);
}
else if (input != "s")
{
assert(false);
}
// stops!
}
else
{
assert(false);
}
}
void get_num_or_nested(std::stringstream& eq)
{
std::cout << "Insert one of the following:\n";
std::cout << "A number\n";
std::cout << "n for Nested" << std::endl;
std::string input = get_input_from_user();
if (input == "n")
{
eq << "(";
get_num_or_nested(eq);
eq << ")";
get_operation_or_stop(eq);
}
else if (is_number(input))
{
eq << input;
get_operation_or_stop(eq);
}
else
{
assert(false);
}
}
int main()
{
std::cout << "Welcome to the equation builder!\n" << std::endl;
std::stringstream eq;
get_num_or_nested(eq);
std::cout << "The equation you have built is... " << eq.str() << std::endl;
std::cout << "Thanks for coming!" << std::endl;
}
The only thing that is wrong is when the user says yes to nesting. Instead of calling the function and discarding what it returned, you need to return what the function returned.
if(nesting == "y")
{
nested = true;
tab += "\t";
return buildEq(true, tab);
}
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.
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.
I'm writing a program that acts as a calculator; based on the character input by the user it performs a certain operation. The structure of the program seems to work fine, but I'd like to be able to check for erroneous input. After receiving the float variable, is there any way to check if it does not contain any characters other than digits and decimals? I've tried isdigit, and this:
if (!(cin >> x)) {
cout << "You did not enter a correct number!" << endl;
return;
}
But nothing seems to be working.
Here is a sample of one of the simple operation functions I'm using:
void Add(){
float x = 0, y = 0, z = 0;
cout << "Please enter two numbers you wish "
<< "to add separated by a white space:" << endl;
cin >> x >> y;
z = x+y;
cout << x << " + " << y << " = " << z << "." << endl;
return;
}
You test the state of the stream:
float x, y;
if (std::cin >> x >> y) {
// input extraction succeeded
}
else {
// input extraction failed
}
If this isn't working for you, then you need to post the exact code that isn't working.
To detect erroneous string input where you expected a number, C++ doesn't automatically know what you want, so one solution is to first accept your input as strings, validate those strings, then if valid, only then convert the strings to float numbers using the atof() function.
The standard string class has a function called find_first_not_of() to help you tell C++ which characters you consider valid. If the function finds a character not in your list, it will return the position of the bad character, otherwise string::npos is returned.
// add.cpp
#include <iostream>
#include <string>
#include <cstdlib> // for atof()
using namespace std;
void Add()
{
cout << "Please enter two numbers you wish "
<< "to add, separated by a white space:"
<< endl;
string num1, num2;
cin >> num1;
if( num1.find_first_not_of("1234567890.-") != string::npos )
{
cout << "invalid number: " << num1 << endl;
return;
}
cin >> num2;
if( num2.find_first_not_of("1234567890.-") != string::npos )
{
cout << "invalid number: " << num2 << endl;
return;
}
float x = 0, y = 0, z = 0;
x = atof( num1.c_str() );
y = atof( num2.c_str() );
z = x+y;
cout << x << " + " << y << " = " << z << "." << endl;
}
int main(void)
{
Add();
return 0;
}
One possibility would be to read the input as a string, then use boost lexical_cast to convert to floating point. lexical_cast only considers the conversion successful if the entire input converts to the target -- otherwise, it'll throw a bad_lexical_cast exception.
Another idea would be to test the input against a regex. An example regex for a float could be
-?[0-9]+([.][0-9]+)?
This method would also make it easier to refine the matching mechanism by only modifying the regex, and you could map multiple regular expressions against different types of input, for example an integer could then be expressed as
-?[0-9]+
and so on. Keep in mind however, that this only tests if the input is a valid format, it still requires a numerical conversion afterwards (I prefer boost::lexical_cast).
(You can also try it out with http://gskinner.com/RegExr/)