Basic C++ calculator - c++

I'm quite new to C++. This is what I'm disposing with at the moment and I suppose you can guess the logic I'm trying to apply to the program so that it may work. I need the user to supply an arithmetic to be performed and if it's a certain one to add the numbers together. Here is the code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int x;
int v;
int sum;
string input;
cout << "Choose arithmetic: addition or subtraction? " << endl;
cin >> input;
if(input=='Addition'||input=='addition')
{
int first;
int second;
int sum = first+second;
cout << "Enter the first number: " << endl;
cout << "Enter the second number: " << endl;
cout << "The sum of these numbers is: " << sum << endl;
}
return 0;
}
The compiler gives me the following error:
13 error: no match for 'operator==' in 'input == 1953066862'
Thank you in advance!

Literal strings in C++ use double quotes, not single quotes. That is, "Addition" instead of 'Addition'.
A single-quoted string is something called a "multi-character constant" which is valid but definitely not what you want here.

In C/C++, a string should be in "" rather than ''. It should be "Addition".

Try using double quotation marks (") instead of single quotation marks (') on the following line:
if(input=='Addition'||input=='addition')

In C++, literal/constant character strings are wrapped in double quotes (e.g. "string"). Literal/constant single characters are wrapped in single quotes ('c').
As it's good programming practice, you may also want to convert your user's input to lowercase and then perform the conditional (use the function tolower()). That way you can cover all upper/lower case permutations :).
tolower function for C++ strings

u can use just an operator, check this out:
http://www.programmingtunes.com/a-simple-calculator-in-c/
you just enter your complete statement here and get your answer.
eg: 5+6

Related

Characters after a space is not being printed out

I was using character arrays to get inputs from the user then display the output afterwards. However, every time I enter values with spaces in between, only the first word before the space is printed.
For instance, this is what I typed:
Customer No.: 7877 323 2332
This will be the output:
Customer No.: 7877
I already searched for possible solutions but I can't seem to find the right solution.
This is my code for reference:
#include<iostream>
using namespace std;
int main()
{
char custNum[10] = " "; // The assignment does not allow std::string
cout << "Please enter values for the following: " << endl;
cout << "Customer No.: ";
cin >> custNum;
cout << "Customer No.: " << custNum << endl;
}
Another option is to use std::basic_istream::getline to read the entire string into the buffer and then remove the spaces with a simple for loop. But when using plain-old character arrays don't skimp on buffer size. It is far better to be 1000-characters too long than one-character too short. With your input, your absolute minimum size of custNum is 14 characters (the 13 shown plus the '\0' (nul-terminating) character. (rough rule-of-thumb, take your longest estimated input and double it -- to allow for user-mistake, cat stepping on keyboard, etc...)
In you case you can simply do:
#include <iostream>
#include <cctype>
int main() {
char custNum[32] = " "; // The assignment does not allow std::string
int wrt = 0;
std::cout << "Please enter values for the following:\nCustomer No.: ";
if (std::cin.getline(custNum, 32)) { /* validate every input */
for (int rd = 0; custNum[rd]; rd++)
if (!isspace((unsigned char)custNum[rd]))
custNum[wrt++] = custNum[rd];
custNum[wrt] = 0;
std::cout << "Customer No.: " << custNum << '\n';
}
}
The two loop counters rd (read position) and wrt (write position) are simply used to loop over the original string and remove any whitespace found, nul-terminating again when the loop is left.
Example Use/Output
$ ./bin/readcustnum
Please enter values for the following:
Customer No.: 7877 323 2332
Customer No.: 78773232332
Also take a look at Why is “using namespace std;” considered bad practice? and C++: “std::endl” vs “\n”. Much easier to build good habits now than it is to break bad ones later... Look things over and let me know if you have questions.
Apart from std::getline, if you are going to use C-style strings, try the following code:
int main() {
char* str = new char[60];
scanf("%[^\n]s", str); //accepts space a a part of the string (does not give UB as it may seem initially
printf("%s", str);
return 0;
}
Also, if you absolutely need it to be a number, then use atoi
int ivar = std::atoi(str);
PS Not to forget gets (!!dangerous!!)
char* str;
gets(str);
puts(str);
cin >> int_variable will stop reading input when it reaches the first character that isn't a valid part of a number. C++ does not consider spaces part of a number, so it stops reading as soon as it encounters one.
You could use std::getline to read into a string instead, then remove the spaces from the string before converting to an integer. Or maybe in this case you don't even need the integer and can leave it as a string.

How to show a specific character in an array of string or char from a different class

Beginner in c++ and programming here. If this sounds stupid then you know why.
I'm trying to compare a variable to a specific character in an array of string or char. It works, when I compare it to a . I want to use the "if" function, but are there any other way of doing it? C++
I tried doing if(variable == Obj.ArrayofString[0][1]) and if(variable == b[0][0]) doesn't work
#include "DataBase.h"
#include <iostream>
#include <string>
using namespace std;
string input;
string b[] = {"Lol","Fight"};
int main()
{
DataBase Bo;
cout << "Type a letter" << endl;
cin >> input;
if (input == Bo.Words[0]){
cout << "Got one" << endl;
}
cout << Bo.Words[0][0];
return 0;
}
**enter code here**
When I try to compare a specific variable to a specific character from a specific element in an array, I get an error. Plz help. Check the red line at the bottom in the "Build messages" tab
no match for 'operator==' (operand types are 'std::_cxxll::string {aka std::_cxll and some other stuff
The issue here is that you are trying to compare a string to a char. These two are different types. For example, your input could contain multiple letters.
The solution is simple: Take the first character of your input string.
if (input[0] == Bo.Words[0][0]){
cout << "Got one" << endl;
}
I assume here that Bo.Words[0] is also of type std::string. Also, I refer to your linked code. In your posted code, you have Bo.Words[0] instead of Bo.Words[0][0].

Why does this C++ program round double values and not print the whole string?

I was working on a HackerRank problem and I could not figure out why the C++ code round the double values when I am adding them and why it does not take in/print the entire string input it is given.
The code is supposed to take in an integer input (from one line), a double input (from another line), and a string input (also, from another line). Then it is supposed to print out the sum of the int input and 4, the sum of the double input and 4.0, and concatenate the string "HackerRank" to the beginning of the input string.
Here's the code I have:
#include <iostream>
#include <iomanip>
#include <limits>
int main(){
int i = 4;
double d = 4.0;
string s = "HackerRank";
// Declare second integer, double, and String variables.
// Read and save an integer, double, and String to your variables.
// Note: If you have trouble reading the entire string, please go back and review the Tutorial closely.
// Print the sum of both integer variables on a new line.
// Print the sum of the double variables on a new line.
// Concatenate and print the String variables on a new line
// The 's' variable above should be printed first.
int a;
double b;
string c;
cin >> a;
cin >> b;
cin >> c;
a = a + i;
b = b + d;
cout << a << endl;
cout << b << endl;
cout << "" + s + c;
return 0;
}
For the following input:
12
4.0
is the best place to learn and practice coding!
I got the output:
16
8
HackerRank is
When this is the expected output:
16
8.0
HackerRank is the best place to learn and practice coding!
The answer to your 2 questions:
Firstly, when you add a value of type int to a value of type float/string, the result will be of type int. This explains why you the output is 8 and not 8.0. This same rule applies to multiplication, division, and subtraction. Whenever an int is operated on by a float/double value or vice versa, the result is always of type int. Therefore, you should change the initialization of your d value to:
double d = 4.0; // Or float d = 4.0
By the way, you cannot add a decimal point to a value of type int and expect it to be a floating point/double value. The data type of the variable that stores the value must be defined/initialized with a certain data type.
Secondly, your code does not print the desired string as you are using the wrong function to get the string as input from the user. While cin is the norm to be used in input, it does not work so well with variables of type "string". The reason for this is because cin only accepts one word; one continuous int, floating point value, char, etc..., and it cannot accept an entire sentence with spaces in between because it just stops reading after it sees a space; that's the rules of cin. To bypass this problem, you'll need another function, and that is
getline(cin, variable_to_store_data);
instead of doing:
cin >> c;
Do this:
getline(cin, c);
This way, the entire sentence you inputted will be stored in the variable and not just the first word of the sentence. The getline does not ignore the words in a sentence that come after the first one; it reads all of the user input till the point he/she hits Enter, and it then stores the entire value in the variable (that's the second parameter).
By the way, if you want to output multiple things in one cout line, then do it using the following template:
cin << a << ... << z << endl; // endl is optional; depends on your needs
Avoid using the method you used above:
cout << "" + s + c;
Do it this way:
cout << "" << s << c; // Why do you have "" at the begninning? That prints nothing. You can take that off also.
On a side note, getline() also has a lot of other functions, such as reading lines from a file. Read more about it online; there are lots of resources available.
Hope this answers your question.
EDIT: To make the program work, you'll actually have to add another line to ignore the enter hit at the end of the cin >> b; command, because that saves as the string in c. Therefore, do this:
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
getline(cin, c);
The line I just added ignores the newline character hit at the end of the cin >> b command. This way, the compiler goes on to ask the user for the string to be stored in c. I've tried this code, and it works as it should.
Another thing, change your output statement to;
cout << "" << s << " " << c << "." << endl;
This makes the string easier to read, and it adds a space between variable s and variable c during output. Hope this helps!
This code will work...
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
int i = 4;
double d = 4.0;
string s = "HackerRank ";
int i2;
double d2;
string s2;
cin>>i2;
cin>>d2;
cin.ignore();
getline(cin, s2);
cout<<i2+i<<endl;
cout.precision(1);
cout << fixed << d+d2 << endl;
cout<<s+s2;
return 0;
}
You can use the function 'getline' to realize it.
And the following example is well done on VS2013.
#include <string>
#include <iostream>
using namespace std;
int main(){
string c;
getline(cin, c); // is there anybody ?
cout << "Hello, " + c; // Hello, is there anybody ?
system("pause");
return 1;
}
cin>>b;
use cin.ignore();
and then getline(cin, string_name);
This will read the complete string.

C++ stringstream, if word is numeric, divide by two

I am fairly new to programming and have to create a program which reads the prompt: "I have 8 dollars to spend." It then needs to print out with each word on a separate line, and then if any of the strings is numeric, it needs to be divided by 2. Therefore it should end up printing out as:
I
have
4
dollars
to
spend.
I have managed to do everything, except finding the numeric value and dividing it by 2. So far I have this:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string prompt;
string word;
cout << "Prompt: ";
getline(cin, prompt);
stringstream ss;
ss.str(prompt);
while (ss >> word)
{
cout << word << endl;
}
return 0;
}
After looking through various other posts, I cannot manage to get this to work. I'm assuming its an if/else statement within the while loop along the lines of, if numeric, set int num to num / 2 then cout << num << endl;, else cout << word << endl;, but I can't figure it out.
Thanks in advance.
You can use the stringstream class, which handles conversions between strings and other data types, to attempt to convert a given string to a number. If the attempt is successful, you know
The stringstream object allows you to treat a string as though it is a stream similar to cin or cout.
Incorporate this into your while loop, like so:
while (ss >> word)
{
int value = 0;
stringstream convert(word); //create a _stringstream_ from a string
//if *word* (and therefore *convert*) contains a numeric value,
//it can be read into an _int_
if(convert >> value) { //this will be false if the data in *convert* is not numeric
cout << value / 2 << endl;
}
else
cout << word << endl;
}
The strtol (C++11 version that works on std::string directly: std::stol) function is really good for testing whether a string holds a number, and if so, what the numeric value is.
Or you could continue using iostreams like you have been... try extracting a number (int or double variable), and if that fails, clear the error bit and read a string.
I dont have 50 rep so I cant comment, thats why I'm writing it as answer.
I think you can check it character by character, using Ascii value of each char, & if there are ascii values representing numbers between two spaces(two \n in this case as you've already seperated each word), then you have to divide the number by 2.

Check variable type in C++

So I am currently learning C++ and decided to make a program that tests my skills I have learned so far. Now in my code I want to check if the value that the user enters is a double, if it is not a double I will put a if loop and ask them to reenter it. The problem I have is how do I go about checking what type of variable the user enters, ex- if a user enters a char or string, I can output an error message. Here is my code:
//cubes a user entered number
#include <iostream>
using namespace std;
double cube(double n); //function prototype
int main()
{
cout << "Enter the number you want to cube: "; //ask user to input number
double user;
cin >> user; //user entering the number
cout << "The cube of " << user << " is " << cube(user) << "." << endl; //displaying the cubed number
return 0;
}
double cube (double n) //function that cubes the number
{
return n*n*n; // cubing the number and returning it
}
Edit: I would have to say I just started and don't have the slightest of clue about your code, but I will check out your link. By the way, I haven't learned how to work with templates yet,I am learning about dealing with data, only Chapter 3 in my C++ Primer Plus 5th edition.
Safe C++ Way
You can define a function for this using std::istringstream:
#include <sstream>
bool is_double(std::string const& str) {
std::istringstream ss(str);
// always keep the scope of variables as close as possible. we see
// 'd' only within the following block.
{
double d;
ss >> d;
}
/* eat up trailing whitespace if there was a double read, and ensure
* there is no character left. the eof bit is set in the case that
* `std::ws` tried to read beyond the stream. */
return (ss && (ss >> std::ws).eof());
}
To assist you in figuring out what it does (some points are simplified):
Creation of a input-stringstream initialized with the string given
Reading a double value out of it using operator>>. This means skipping whitespace and trying to read a double.
If no double could be read, as in abc the stream sets the fail-bit. Note that cases like 3abc will succeed and will not set the fail-bit.
If the fail-bit is set, ss evaluates to a zero value, which means false.
If an double was read, we skip trailing whitespace. If we then are at the end of the stream (note that eof() will return true if we tried to read past the end. std::ws does exactly that), eof will return true. Note this check makes sure that 3abc will not pass our check.
If both cases, right and left of the && evaluate to true, we return true to the caller, signaling the given string is a double.
Similar, you check for int and other types. If you know how to work with templates, you know how to generalize this for other types as well. Incidentally, this is exactly what boost::lexical_cast provides to you. Check it out: http://www.boost.org/doc/libs/1_37_0/libs/conversion/lexical_cast.htm.
C Way One
This way has advantages (being fast) but also major disadvantages (can't generalized using a template, need to work with raw pointers):
#include <cstdlib>
#include <cctype>
bool is_double(std::string const& s) {
char * endptr;
std::strtod(s.c_str(), &endptr);
if(endptr != s.c_str()) // skip trailing whitespace
while(std::isspace(*endptr)) endptr++;
return (endptr != s.c_str() && *endptr == '\0');
}
strtod will set endptr to the last character processed. Which is in our case the terminating null character. If no conversion was performed, endptr is set to the value of the string given to strtod.
C Way Two
One might thing that std::sscanf does the trick. But it's easy to oversee something. Here is the correct way to do it:
#include <cstdio>
bool is_double(std::string const& s) {
int n;
double d;
return (std::sscanf(s.c_str(), "%lf %n", &d, &n) >= 1 &&
n == static_cast<int>(s.size()));
}
std::sscanf will return the items converted. Although the Standard specifies that %n is not included in that count, several sources contradict each other. It's the best to compare >= to get it right (see the manpage of sscanf). n will be set to the amount of the processed characters. It is compared to the size of the string. The space between the two format specifiers accounts for optional trailing whitespace.
Conclusion
If you are a beginner, read into std::stringstream and do it the C++ way. Best not mess with pointers until you feel good with the general concept of C++.
There is no suitable way to check if a string really contains a double within the standard library. You probably want to use Boost. The following solution is inspired by recipe 3.3 in C++ Cookbook:
#include <iostream>
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace boost;
double cube(double n);
int main()
{
while(true)
{
cout << "Enter the number you want to cube: ";
string user;
cin >> user;
try
{
// The following instruction tries to parse a double from the 'user' string.
// If the parsing fails, it raises an exception of type bad_lexical_cast.
// If an exception is raised within a try{ } block, the execution proceeds
// with one of the following catch() blocks
double d = lexical_cast <double> (user);
cout << "The cube of " << d << " is " << cube(d) << "." << endl;
break;
}
catch(bad_lexical_cast &e)
{
// This code is executed if the lexical_cast raised an exception; We
// put an error message and continue with the loop
cout << "The inserted string was not a valid double!" << endl;
}
}
return 0;
}
double cube (double n)
{
return n*n*n;
}
sscanf can do what you want; it returns the number of arguments properly processed. This should get you started:
//cubes a user entered number
#include <iostream>
#include <cstdio>
using namespace std;
double cube(double n); //function prototype
int main()
{
cout << "Enter the number you want to cube: "; //ask user to input number
string user;
cin >> user; //user entering the number
// Convert the number to a double.
double value;
if(sscanf(user.c_str(), "%lf", &value) != 1)
{
cout << "Bad! " << user << " isn't a number!" << endl;
return 1;
}
cout << "The cube of " << user << " is " << cube(user) << "." << endl; //displaying the cubed number
return 0;
}
double cube (double n) //function that cubes the number
{
return n*n*n; // cubing the number and returning it
}
Other methods posted in other answers have their advantages and disadvantages. This one has issues with trailing characters and isn't "C++"-y.
I would have to say I just started and don't have the slightest of clue about your code, but I will check out your link. By the way, I haven't learned how to work with templates yet,I am learning about dealing with data, only Chapter 3 in my C++ Primer Plus 5th edition.
You can fall back on C and use strtod
You program reads in a string and then passes it to a function that attempts to convert the string into double.
bool is_double(const char* strIn, double& dblOut) {
char* lastConvert = NULL;
double d = strtod(strIn, &lastConvert);
if(lastConvert == strIn){
return false;
} else {
dblOut = d;
return true;
}
}