I am trying to write a program that takes two numbers and allows the user to input either a, s, m, or d. Basically what I am trying to do is make the characters mean addition, subtraction, multiplication and division respectively. The problem is though is I am unsure of how to do it. Here is the code I have so far.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
double num1;
double num2;
char operation;
cout<<"Enter the first number: ";
cin>>num1;
cout<<"Enter the second number: ";
cin>>num2;
cout<<"What would you like to do with the numbers? a-addition, s=subtraction, m=multiplacation, d=division";
cin>>operation;
Check the switch statement:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
double num1;
double num2;
char operation;
cout<<"Enter the first number: ";
cin>>num1;
cout<<"Enter the second number: ";
cin>>num2;
cout<<"What would you like to do with the numbers? a-addition, s=subtraction, m=multiplacation, d=division";
cin>>operation;
switch(operation)
{
case 'a':
... // Addition code
break;
case 's':
... //Substraction code
break;
...
}
You could also just use if and else, one for each type of operation.
Also, just as a tip, consider validating your input data (try typing more characters into your program, or invalid options).
You use a switch:
switch (operation) {
case 'a': // addition
break;
case 's': // subtraction
break;
// ...
default: // none of these
break;
}
Related
I am trying to create a calculator but this happens..
Here's my code. Please help me fix it and give some explanation:
#include <iostream>
using namespace std;
int main()
{
int a;
int b;
string c;
string d;
cout<<"Enter No. 1: ";
cin>>a;
cout<<"Enter Operation: ";
cin>>c;
cout<<"Enter No. 2: ";
cin>>b;
cout<<"So you want me to solve this: ";
cout<<a<<c<<b;
cout<<"Type Yes or No";
cin>>d;
if(d="yes"){
switch(c)
{
case '+':
cout << a+b;
break;
case '-':
cout << a-b;
break;
case '*':
cout << a*b;
break;
case '/':
cout << a/b;
break;
}
}
else{
return 0;
}
}
This is the eroor of the code when compiled pleasee fix this code ima noob:
main.cpp: In function ‘int main()’:
main.cpp:21:9: error: could not convert ‘d.std::basic_string<_CharT, _Traits, _Alloc>::operator=, std::allocator >(((const char*)"yes"))’ from ‘std::basic_string’ to ‘bool’
if(d="yes"){
~^~~~~~
main.cpp:22:17: error: switch quantity not an integer
switch(c)
The error says it, the test in a switch must be an integer, but you have a string.
Also you are getting confused between string which is multiple characters (e.g. "abc") and char which are single characters (e.g. 'a', 'b', or 'c').
To fix use just change
string c;
to
char c;
This works because you only ever want a single character in c so char is the appropriate type, and also because char in C++ is a kind of integer, so it can be used in a switch.
You have another error here
cout<<"Type Yes or No";
cin>>d;
if(d="yes"){
First problem is that you ask the user to enter Yes or No but you test for "yes", "Yes" and "yes" are not the same string.
Second problem is that the test for equality is == not =. = is used for assignment, which is not the same as testing for equality.
There are two major problems here:
You are providing a std::string in switch, this is not possible. You can only pass a character or an integer into it. You could convert that to a char type instead.
There is one logical error is made in the conditional line (notice comment):
if(d="yes") // it should be d == "yes"
Expected behavior is to take the name as input and run the while loop again but instead it just goes to the next line and does nothing.
#include <iostream>
using namespace std;
int main()
{
int ch,mb;
bool y=true;
char name;
cout<<"Enter 1,2 or 3 : ";
do{
cin>>ch;
switch(ch)
{
case 1:
cout<<" \n\t 1.ENTER CUSTOMER NAME :";
cin>>name;
continue;
case 2:
cout<<" \n\t 2.ENTER MOBILE NUMBER:";
cin>>mb;
continue;
case 3:
y=false;
}
}while(y!=false);
}
It doesn't "do nothing"; it waits for the next input. Because that's what you told it to do!
If you want to get another prompt, move the cout<<"Enter 1,2 or 3 : "; line inside the loop.
By the way, a char is one byte so that's not really appropriate for reading a whole customer name; furthermore, you should avoid using ints for telephone numbers.
Use break; instead of continue;
break will move execution to the end of the switch.
Edit: I think the issue is that you are just not seeing your prompt again. so move it inside your loop.
The task I have is to make a vector of strings, append strings to it, and delete strings from it. I am having trouble with append strings.I also have it set up so that the switch case gives the option to append the queue in case 1.
//gaming Queue
#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
int choice;
string input;
bool menu = true;
vector<string> favGames;
while (menu){
cout <<"Welcome to the favorite game queue please add your favorite games:\n";
cout <<"1-Add a favorite game.\n";
cout <<"2-List of your favorite games.\n";
cout <<"3-Remove a game.\n";
cin >> choice;
switch (choice)
{
case 1:
cout << "Please add a favorite game to the queue: \n";
string input;
cin >> input;
favGames.push_back(input);// Here is my problem it just jumps to case 2 and shows an error
break;
case 2:
cout << "Here is a list of your favorite games.\n";
break;
default:
cout << "You made an illegal choice.\n";
}
}
return 0;
}
switch statements are a bit weird because you can't declare variables inside the case clauses unless you create a scope for them using a {} block.
switch (choice)
{
case 1:
{ // start a scope
cout << "Please add a favorite game to the queue: \n";
string input;
cin >> input;
favGames.push_back(input);// Here is my problem it just jumps to case 2 and shows an error
break;
} // end the scope
However in your case you already defined a std::string outside the switch, did you intend to use that? Then you can just remove the one inside the case clause.
When compiling your code on https://www.onlinegdb.com/online_c++_compiler, it shows me those error:
main.cpp:34:18: error: jump to case label [-fpermissive]
case 2:
^
main.cpp:30:24: note: crosses initialization of 'std::string input'
string input;
as you can see the compiler tells you that you're skipping the initialization of string input. At the same time you are declaring input a second time.
By removing input inside the switch case, the program compiles and works as intended.
EDIT:
You can't enter more than one word using cin because cin extraction always considers spaces (whitespaces, tabs, new-line...) as terminating the value being extracted.
So you have to use getline. Same for when getting choice.
here is the full code:
#include "stdafx.h"
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
int choice;
string input;
bool menu = true;
vector<string> favGames;
while (menu) {
cout << "Welcome to the favorite game queue please add your favorite games:\n";
cout << "1-Add a favorite game.\n";
cout << "2-List of your favorite games.\n";
cout << "3-Remove a game.\n";
string choiceStr;
getline(cin, choiceStr);
stringstream(choiceStr) >> choice;
switch (choice)
{
case 1:
cout << "Please add a favorite game to the queue: \n";
getline(cin, input);
favGames.push_back(input);
break;
case 2:
cout << "Here is a list of your favorite games.\n";
break;
case 3:
cout << "No longer like a game which game should we remove?\n";
break;
default:
cout << "You made an illegal choice.\n";
}
}
return 0;
}
The reason why it enters infinite loop:
The cin >> input can only work when you enter only one word. If you enter several words, the cin >> input will catch the first one then the cin >> choice will catch the next one. If the input catch by cin >> choice is not an int, the cin will fail which makes you an infinite loop in this case.
It is explained here http://www.cplusplus.com/doc/tutorial/basic_io/.
New to Stack and C++.
I want to terminate a loop that regurgitates numbers fed to it with a character. Say, Q for Quit. The following program is functional and free of syntax errors. How can I terminate this loop without editing the input parameter?
#include <iostream>
#include <string>
using namespace std;
int main()
{
bool run = true;
while(run)
{
cout<<"Enter your two favorite numbers."<<endl;
int num1;
int num2;
cin>>num1>>num2;
cout<<"You entered "<<num1<<" and "<<num2<<"."<<endl;
}
return 0;
}
You want the break statement. But you'll also then need to read a string for the first input, rather than an integer.
while(run)
{
cout<<"Enter your two favorite numbers, or 'Q' to exit."<<endl;
string input;
int num1;
int num2;
cin>>input1;
if (input == "Q")
{
break;
}
else
{
num1 = stoi(input);
}
cin>>num2;
cout<<"You entered "<<num1<<" and "<<num2<<"."<<endl;
}
I am trying to get a vector to store objects of class 'Complex'.
This is how I have tried to get it to store:
ifstream values;
values.open("h://values.txt");
if(!values)
{
cout<<"Error: cannot open "<<"values.txt"<<endl<<endl;
}
else
{
//Initialise list
vector<Complex> v;
Complex *c1;
double a,b,d=0,e=0;
char c;
int count=0;
while(values)
{
values>>c>>a>>b;
c1=new Complex;
v.push_back(*c1);
cout<<c<<" "<<a<<" "<<b<<endl;
switch (c)
{
case 'r':
case 'R':
case 'p':
case 'P':
{
//Call constructor
v[count].setType(c);
switch (c)
{
case 'r':
case 'R':
{ v[count].setReal(a);
v[count].setImaginary(b);
v[count].topolar(a,b,d,e);
break;
}
case 'p':
case'P':
{ v[count].setLength(a);
v[count].setAngle(b);
v[count].frompolar(d,e,a,b);
break;
}
default:
{ cout<<"Type Error"<<endl;
break;
}
}
count++;
break;
}
default:
{
//error message
cout<<" Failed input type, ensure all of type 'r' or 'p'"<< endl;
cout<<"Programme Closing"<<endl;
break;
}
};
}
While this will read the info in my programme, it insists on reading the last line twice (I put the cout into this loop so it was easier to see what numbers were where). I have tried using a for loop, but because I want it to run till the end of file I think I have to use a while loop, but I might be wrong.
My supervisor said something along the lines of c1 being overwritten on every loop, but I thought this should be OK on the basis the information is passed to the vector before it is overwritten by the next line so I'm a bit confused.
The next problem is that when I then try and print out all the information again, outside of the loop shown above (for example to allow for manipulation before printing) it prints the same thing over and over until the for loop reaches the count...
int y;
int z;
while(y!=3)
{
cout<< " What would you like to do?"<<endl;
cout<< " Type the number of the option you would like"<<endl;
cout<< " 1. Show all numbers in polar form"<<endl;
cout<< " 2. Show all numbers in rectangular form"<<endl;
cout<< " 3. Show all numbers in both forms"<<endl;
cout<< " 4. Convert a number to its conjugate"<<endl;
cout<< " 5. Exit"<<endl;
cin>>y;
switch(y)
{
case 1:
for(z=0; z<count;z++)
{
v[z].getLength();
v[z].getAngle();
cout<< a<<" "<<b<<endl;};
break;
case 2:
for (z=0; z!=count;z++)
{
v[z].getReal();
v[z].getImaginary();
};
break;
case 3:
cout<<" Real Imaginary | Length Angle | Original Type"<<endl;
for(z=0; z!=count;z++)
{ v[z].getLength();
v[z].getAngle();
v[z].getReal();
v[z].getImaginary();
cout<<a<<" "<<b<<" "<<d<<" "<<e<<endl;
In case any of you try to run the programme:
#include "Class definitions.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string.h>
#include <cmath>
#include <vector>
using namespace std;
Any help will be greatly appreciated!!
Thanks muchly!
H
x
Whether input succeeds is only known after the input, not before. After you do
values>>c>>a>>b;
you use the values, even if the input has failed (e.g. because of end of file). Put the test in the condition of the while loop:
while ( values >> c >> a >> b )
and your code should work. (Whether this is the best way to handle the problem is another question. I'd probably use std::getline(), followed by std::istringstream to parse the line I'd read. Much easier error recovery.)