C++ Coding Issue - c++

I am getting this error as I am trying to compile my code. I am trying to make a simple calculator and I am having some trouble removing this final error. Any and all help is appreciated.
The error I am getting is as follows expected constructor, destructor, or type conversion before '(' token
#include <iostream>
#include <string.h>
using namespace std;
int intevaluate(int Left, char Operation, int Right);
void Intro();
int intLeft;
int intRight;
char charOperation;
int intAddition;
int intSubtraction;
int intMultiplication;
int intDivision;
void Intro()
{
cout << "These are the arithmetic operations you can choose to enter ";
cout << " + for addition\n - for subtraction\n * for multiplication\n and / for division\n";
}
intevaluate(intLeft, charOperation, intRight)
{
intAddition = intLeft + intRight;
intSubtraction = intLeft - intRight;
intMultiplication = intLeft * intRight;
intDivision = intLeft / intRight;
if (charOperation == "+")
{
cout << "The answer is " << intAddition;
}
else if (charOperation == "-")
{
cout << "The answer is " << intSubtraction;
}
else if (charOperation == "*")
{
cout << "The answer is " << intMultiplication;
}
else if (charOperation == "/") && ( Left || Right != 0)
{
cout << "The answer is " << intDivision;
}
else if (charOperation == "/") && ( Left || Right == 0)
{
cout << "You cannot divide by zero ";
}
}
int main()
{
cout << "Please enter an integer value and press enter: ";
cin >> intLeft;
cout << "\nPlease enter another integer value and press enter: ";
cin >> intRight;
Intro();
cout << "\nPlease enter an arithmetic operation from the list above and press enter: ";
cin >> charOperation;
intevaluate(intLeft, charOperation, intRight);
return 0;
}

You have messed up the function argument names.
if (Operation == +)
{
// ...
}
What is Operation? You pass the function a char with argument name
charOperation
not
Operation
You can't compare characters like that. You must do
if(charOperation == '+')
and so on.

Related

Give an output when a string is a certain word?

#include <iostream>
using namespace std;
int main()
{
string n;
cout << "Enter the name of an automobile: " << endl;
cin >> n;
while( n != "End") {
if( n == ("Tesla" or "Volt" or "Leaf")) {
cout << "Electric" << endl;}
else {
if( n == ("Clarity" or "Mirai")){
cout << "Hydrogen Powered" << endl;}
else {
cout << "Gas Powered" << endl; }}
cout << "Enter the name of an automobile: " << endl;
cin >> n;
}
return 0;
}
It needs to say how each automobile is powered. Basically if I input "Tesla", it should say "Electric"; "Ford" should come up "Gas Powered". It ends when I enter "End".
I get this error
.cpp|16|error: invalid operands to binary expression ('std::__1::string' (aka 'basic_string, allocator >') and 'bool')|
This should work! In C++ there is no or. Use ||. Also the condition needs to be put each time in if like if(n=="Tesla"||n=="Volt"||n=="Leaf").
#include <iostream>
using namespace std;
int main()
{
string n;
cout << "Enter the name of an automobile: " << endl;
cin >> n;
while( n != "End") {
if( n == "Tesla" || n== "Volt" ||n== "Leaf") {
cout << "Electric" << endl;}
else {
if( n == "Clarity" || n=="Mirai"){
cout << "Hydrogen Powered" << endl;}
else {
cout << "Gas Powered" << endl; }}
cout << "Enter the name of an automobile: " << endl;
cin >> n;
}
return 0;
}
if( n == ("Tesla" or "Volt" or "Leaf"))
needs to be changed to
if( (n == "Tesla") || (n == "Volt") || (n == "Leaf") )
Make similar changes at the other places where you do the same thing
There is no or keyword in C++. You need to use ||
("Tesla || "Volt" || "Leaf") would always return true. So the condition will become if (n == (true)) which will never be true.

How to Accept [ENTER] key as an invalid input and send out error message

This is a program that grade user inputs for the questions of Driver's License Exam.
I'm having trouble of validating the user input.
I'd like to accept the [ENTER] key as an invalid input and proceed to my validation rather than just go to an empty line and cannot process to the next question. Purpose is to send out error message and that no input is given and [ENTER] key is not valid input and only accept one more chance to enter valid input which are a/A, b/B, c/C, or d/D. So that is why I'm using if statement here instead of loop.
I tried if (testTakerAnswers[ans] == (or =) '\n') {} but still doesn't solve the problem of newline.
I include curses.h in here hope to use getch() statement from the other post but somehow I can't manage to work in my code with an array instead of regular input.
I'm looking for other methods as well rather than getch()
So should I adjust my bool function, or directly validate input in main() function.
#include <iostream>
#include <iomanip>
#include <string>
#include <cctype>
#include <curses.h>
using namespace std;
const unsigned SIZE = 20; // Number of qns in the test
char testTakerAnswers[SIZE]; //Array to hold test taker's answers
bool validateInput(char);
class TestGrader
{
private:
char answers[SIZE]; // Holds the correct answers // Answer is array
int getNumWrong (char[]);
void missedQuestions (char[]);
public:
void setKey(string); // Initialize object with standard keys
void grade(char[]); // Grades the answers from tester
};
void TestGrader::setKey(string key){
if (key.length()!=SIZE){
cout << "Error in key data.\n";
return;
}
for (unsigned pos = 0; pos < SIZE ; pos ++)
answers [pos] = key [pos];
}
void TestGrader::grade(char test[])
{
int numWrong = getNumWrong(test);
if (numWrong <= 5)
cout << "Congratulations. You passed the exam.\n";
else
cout << "You did not pass the exam. \n";
cout << "You got " << (SIZE-numWrong) << " questions correct. \n";
if (numWrong > 0){
cout << "You missed the following " << numWrong << " questions: \n";
missedQuestions(test);
}
}
int TestGrader::getNumWrong(char test[])
{
int counter = 0;
for (int i = 0; i < SIZE; i++){
if (answers[i] != toupper(testTakerAnswers[i])){
counter++;
}
}
return counter;
}
void TestGrader::missedQuestions(char test[])
{
// cout << testTakerAnswers[i]; This is to print taker's answers
int counter = 0;
for (int i = 0; i < SIZE; i++){
if (answers[i] != toupper(testTakerAnswers[i])){
cout << "\n" << i + 1 << ". Correct answers: " << answers[i];
counter++;
}
}
}
bool validateInput(char ans){ // Only A, B, C, D valid input
if (toupper(ans)!='A' && toupper(ans)!= 'B' && toupper(ans)!='C' && toupper(ans)!= 'D'){
cout << "\n********************WARNING*******************\n";
cout << "Invalid input! Enter only a/A, b/B, c/C, or d/D\n";
return false;
}
if (testTakerAnswers[ans] == '\n'){
return false;
}
return true;
}
int main()
{
const int NUM_QUESTIONS = 20;
string name; //Test taker's name
char doAnother; //Control variable for main processing loop
TestGrader DMVexam; //Create a TestGrader object
DMVexam.setKey("BDAACABACDBCDADCCBDA");
do {
cout << "Applicant Name: ";
getline(cin,name);
cout << "Enter answer for " << name << ".\n";
cout << "Use only letters a/A, b/B, c/C, and d/D. \n\n";
for (int i = 0; i < NUM_QUESTIONS; i++){
// Input and validate it
do{
cout << "Q" << i+1 << ": ";
cin >> testTakerAnswers[i];
if (!validateInput(testTakerAnswers[i])){
cout << "You get one more chance to correct.\nOtherwise, it count as wrong answer.";
cout << "\n*********************************************";
cout << "\nRe-enter: ";
cin >> testTakerAnswers[i];
cout << '\n';
break;
}
}while(!validateInput(testTakerAnswers[i]));
}
//Call class function to grade the exam
cout << "Results for " << name << '\n';
DMVexam.grade(testTakerAnswers);
cout << "\nGrade another exam (Y/N)? ";
cin >> doAnother;
while (doAnother != 'Y' && doAnother != 'N' && doAnother != 'y' && doAnother != 'n'){
cout << doAnother << " is not a valid option. Try Again y/Y or n/N" << endl;
cin >> doAnother;}
cout << endl;
cin.ignore();
}while(doAnother != 'N' && doAnother != 'n');
return 0;
}
Your issue is cin >> testTakerAnswers[i]; cin is whitespace delimited, that means that any whitespace (including '\n') will be discarded. So testTakerAnswers[i] can never be '\n'.
I'm not sure exactly what you want to do, but possibly try
getline(cin,input_string);
then
input_string == "A" | input_string == "B" | ...
So if only the enter key is pressed, input_string will become "".

C++ string array & for loop doesnt work as i expected

#include <iostream>
using namespace std;
int main()
{
char num[10];
int a;
cout << "Odd or Even"<< endl;
for(;;)
{
cout << "Enter Number:" ;
cin >> num;
cout << endl;
for(a=9;a>=0;a--)
{
if(num[a]!='\0 && num[a]!=' ')
break;
}
if(num[a]==1 || num[a]==3 || num[a]==5 || num[a]==7 || num[a]==9)
cout << "Odd" << endl;
else
cout << "Even" << endl;
}
}
I am a rookie of C++,and I wrote a program to discriminate if a number is even or odd,
but no matter what number I enter, it only outputs "Even".
So I added these to find out when did the loop breaks:
cout << a << endl;
cout << "\"" << num[a] << "\"" << endl;
Result:
Enter Number:11
9
" "
Even
the for loop beraks when num[9]=' '? Which will lead to else and always output "Even".
You are confused about the character '1' and the number 1. They are different.
Instead of
if(num[a]==1 || num[a]==3 || num[a]==5 || num[a]==7 || num[a]==9)
you need
if(num[a]=='1' || num[a]=='3' || num[a]=='5' || num[a]=='7' || num[a]=='9')
Update
There is one more problems that is probably tripping you up.
num is not initialized. Zero-initialize it. Remember 0 is not the same as the character '0'.
char num[10] = {0};
Move the initialization of num inside the for loop. That will eliminate the problem of data from a previous execution of the loop from affecting the current execution of the loop.
Here's a version that works for me.
#include <iostream>
using namespace std;
int main()
{
cout << "Odd or Even"<< endl;
for(;;)
{
char num[10] = {0};
int a;
cout << "Enter Number:" ;
cin >> num;
cout << endl;
for(a=9;a>=0;a--)
{
if(num[a]!='\0' && num[a]!=' ')
break;
}
cout << num[a] << endl;
if(num[a]=='1' || num[a]=='3' || num[a]=='5' || num[a]=='7' || num[a]=='9')
cout << "Odd" << endl;
else
cout << "Even" << endl;
}
}
PS
You can replace the line
if(num[a]!='\0' && num[a]!=' ')
by
if(isdigit(num[a]))
That makes more sense to me.
If you are doing this with c++ there are much easier ways! Consider the following:
while (!done) {
string inputline;
getline(cin, inputline); //Now we have a string with the users input!
stringstream ss; // stringstreams help us parse data in strings!
int num; // We have a number we want to put it into.
ss >> num; // We can use the string stream to parse this number.
// You can even add error checking!
// Now to check for odd even, what do we know about even numbers? divisable by 2!
if (num % 2 == 0) // No remainder from /2
cout << Even << '\n'
else
cout << Odd << '\n'
}
see how you go with that!
Warning Untested code
You did a mistake (typo) here in this line..
if(num[a]!='\0 && num[a]!=' ')
it should be
if(num[a]!='\0' && num[a]!=' ')

c++ compiler ignoring first if statement

I am a newby at this and am working on my fist if/else program. I am having trouble getting the first if statement to recognize my input of "r". I tried playing with just one statement at a time I was able to input all the examples of input the teacher gave us with the desired output for residential and business. However when I run the program altogether I have a problem. I select R for residential, 0 for additional connections, 0 for premium channels and instead of output of $18.50 I get the business fee of $75.00. I am sure it is a simple mistake but I can't figure out what I am doing wrong. Can someone who knows how to work an if/else give me some insight on this!
#include "stdafx.h"
#include <conio.h>
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const float BASIC_RESIDENTIAL = 18.50;
const float BASIC_BUSINESS = 75.00;
const float CONNECT_RESIDENTIAL = 6.50;
const float CONNECT_BUSINESS = 5.00;
const float PREMIUM_RESIDENTIAL = 7.50;
const float PREMIUM_BUSINESS = 50.00;
char customerType;
int numOfConnections;
int numOfPremiumChannels;
float amountCableBill;
cout << fixed << setprecision(2);
cout << "Residential or Business [R or B]? ";
cin >> customerType;
cout << endl << endl;
cout << "How many Additional Connections? ";
cin >> numOfConnections;
cout << endl << endl;
cout << "Total number of Premium Channels: ";
cin >> numOfPremiumChannels;
cout << endl << endl;
if (customerType == 'R' || customerType == 'r')
{
amountCableBill = BASIC_RESIDENTIAL + CONNECT_RESIDENTIAL * numOfConnections + PREMIUM_RESIDENTIAL * numOfPremiumChannels;
}
//else customerType == 'B' || customerType == 'b'; // unnecessary
{
if (numOfConnections <= 9)
amountCableBill = BASIC_BUSINESS + PREMIUM_BUSINESS * numOfPremiumChannels;
else
amountCableBill = BASIC_BUSINESS + (numOfConnections - 9) * CONNECT_BUSINESS + PREMIUM_BUSINESS *numOfPremiumChannels;
}
cout << "Total amount of Cable Bill: " << amountCableBill << endl << endl;
cout << "Press <ENTER> to end..." << endl;
_getch();
return 0;
}
While the condition else if (customerType == 'B' ...) may be redundant, you still have to put an else before the opening brace of the branch.
It's
if (condition) { code } else { code }
You need else in the condition (unless you want "some other code" to be executed every time)
if (customerType == 'R' || customerType == 'r')
{
//Some Code
}
else //<--Notice else
{
//Some other code.
}

mismatch in formal parameter list

\a3.cpp(75): error C2563: mismatch in formal parameter list
I'm certain I'm passing the function checkout with 3 doubles, I don't know why I'm getting the error I am. Please help.
#include <iostream>
#include <cstdlib>
using namespace std;
const double peanut_PRICE = 1.80;
const double peanut_SHIP = 0.50;
const double BOOK_PRICE = 9;
const double BOOK_SHIP = 1.06;
const double MOVIE_PRICE = 13.99;
const double MOVIE_SHIP = 0.05;
double checkout (double myamountofbooks, double myamountofmovies, double mypoundsofpeanuts)
{
myamountofbooks = myamountofbooks * (BOOK_PRICE + BOOK_SHIP);
myamountofmovies = myamountofmovies * MOVIE_PRICE * (1 + MOVIE_SHIP);
mypoundsofpeanuts = mypoundsofpeanuts * (peanut_PRICE + peanut_SHIP);
return (myamountofbooks + myamountofmovies + mypoundsofpeanuts);
}
bool validUserImput (int whereUserWantsToGoNext)
{
if (whereUserWantsToGoNext > 50 || whereUserWantsToGoNext < 0)
return false;
else return true;
}
bool validUserImput (double whereUserWantsToGoNext)
{
if (whereUserWantsToGoNext > 50 || whereUserWantsToGoNext < 0)
return false;
else return true;
}
int main()
{
//===========================Declaration Statements==================================
double amountofbooks = 0;
double amountofmovies = 0;
double poundsofpeanuts = 0;
int whereUserWantsToGoNext = 0;
while (! (whereUserWantsToGoNext == 4) )
{
cout << "1. Books\n2. Peanuts\n3. Movies\n4. Checkout\n" << endl;
cin >> whereUserWantsToGoNext;
if (!validUserImput(whereUserWantsToGoNext)) cout << "INVALID IMPUT" << endl;
if (whereUserWantsToGoNext == 1){
cout << "Please enter your number of books";
cin >> amountofbooks;
if (!validUserImput(amountofbooks)) cout << "INVALID IMPUT" << endl;
}
if (whereUserWantsToGoNext == 3){
cout << "Now please enter the number of movies you've selected";
cin >> amountofmovies;
if (!validUserImput(amountofmovies)) cout << "INVALID IMPUT" << endl;
}
if (whereUserWantsToGoNext == 2) {
cout << "Please enter the weight(in pounds) of your peanuts";
cin >> poundsofpeanuts;
if (!validUserImput(poundsofpeanuts)) cout << "INVALID IMPUT" << endl;
}
if (validUserImput == 4) cout << "Total Cost is..." << checkout(amountofbooks, amountofmovies, poundsofpeanuts);
}
cin >> amountofbooks;
}
The problem is here:
if (validUserImput == 4) ...
validUserImput is a function, but you are not calling that function, you are trying to compare it to 4.
If you wanted to keep track of the number of valid inputs you received, you could instead add a new variable that you manually increment on every valid input.
The last if - you are comparing function pointer to an integer. try this:
if (validUserImput(3) == 4) cout << "Total Cost is..." << checkout(amountofbooks, amountofmovies, poundsofpeanuts);
I assume you want to display the result of the checkout function if the user selects 4. So you probably wanted to write:
if (whereUserWantsToGoNext == 4) cout << "Total Cost is..." << checkout(amountofbooks, amountofmovies, poundsofpeanuts) << endl;