#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.
Related
The similar question is not what I asking.
Here,
#include <iostream>
using namespace std;
int main(){
int base, inputX;
int aCounter = 0;
do {
std::cout << "Please enter a value between 1-10" << endl;
std::cin >> inputX;
if (!cin) {
std::cout << "Error! number only" << endl;
std::cin.clear();
std::cin.ignore(100, '\n');
}else if (inputX <= 0 && inputX > 18) {
std::cout << "Error! please enter a correct number" << endl;
}else{
base = inputX;
std:;cout << "The number for base is " << base << "." << endl;
aCounter++ ;
}
}while (aCounter == 0);
}
If I input other than number, it loop again and run well.
If I input a number even is 0 or negative, it straight end the loop and print the else statement, what happen to else if?
I think you want to to use or instead of and in else if (inputX <= 0 && inputX > 18)
It will check else if if your code like this:
else if (inputX <= 0 || inputX > 18)
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 "".
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.
#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]!=' ')
I am a beginner and am stuck. I have written this and so far it is not working. After "Add or Remove Trader" it does nothing. Any help or tidbits on how to make this functional would be greatly appreciated. Thank you.
#include<iostream>
#include<iomanip>
#include<string>
using namespace std;
struct Department{
string deptName;
int numTraders;
};
void addTraders(Department *, int );
void removeTraders(Department *, int);
int main(){
char addOrRemove;
Department departments[10] = {
{"Bank Loan", 10},
{"Conservative Allocation", 9},
{"Europe Stock", 10},
{"Domestic", 21},
{"Asia", 10},
{"Large Growth", 5},
{"Long-term Bond", 5},
{"Money Market", 25},
{"Emerging Market", 18},
{"Large Blend", 12}
};
int choice, numberToAdd, numberToRemove;
Department* p_departments = departments;
for(int i = 0; i < 10; i++){
cout << "Department # " << (i + 1) << ", Name: " << p_departments[i].deptName <<
", Traders: " << p_departments[i].numTraders << endl;
}
cout << endl;
do{
cout << "Enter 0 to quit, or choose a department number: ";
cin >> choice;
cout << "Add or remove traders (A or R) ? ";
cin >> addOrRemove;
if(addOrRemove == 'A' || 'a'){
cout << "how many traders to add" << endl;
cin >> numberToAdd;
addTraders(&departments[choice-1] ,numberToAdd);
}
else if(addOrRemove == 'R' || 'r'){
cout << "how many traders to remove" << endl;
cin >> numberToRemove;
removeTraders(&departments[choice-1],numberToRemove);
}
else{
cout << addOrRemove << " is not a valid selection. \n";
}
for(int i = 0; i < 10; i++){
cout << "Department # " << (i + 1) << ", Name: " << p_departments[i].deptName <<
", Traders: " << p_departments[i].numTraders << endl;
}
cout << endl;
}while(count != 0);
system("pause");
return 0;
}
void addTraders(Department *dept, int numAdd){
dept->numTraders += numAdd;
}
void removeTraders(Department *dept, int numRemove){
dept->numTraders += numRemove;
}
The following condition is always evaluated as true; even if it's false || 'a', 'a' ~> true:
if(addOrRemove == 'A' || 'a'){ ...
it was meant to be:
if(addOrRemove == 'A' || addOrRemove == 'a'){ ...
However when addOrRemove is declared as a char, then:
cin >> addOrRemove;
might just read a new-line character or some white space. It would be probably more reasonable to declare addOrRemove as std::string and change your condition to:
if(addOrRemove == "A" || addOrRemove == "a"){ ...
And after you read choice and it's 0, you should break your loop so that it won't try to access element at index 0 - 1:
cin >> choice;
if (choice == 0) break; // <-- THIS
First of all instead of
if(addOrRemove == 'A' || 'a'){
you should write
if(addOrRemove == 'A' || addOrRemove == 'a'){
And secondly you should define variable count because it seems that the compiler thinks that count - is name of standard algorithm std::count.