+ 4
Please Modify My Code
How to Make Calculator Taking input in 1 line using C++ https://sololearn.com/compiler-playground/cpLVlpycztIs/?ref=app
8 ответов
+ 3
Try this:
#include <iostream>
#include <sstream>
using namespace std;
void Calculator(float num1, char op, float num2)
{
float result;
switch (op)
{
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
cout << "Please Enter Correct Operation";
return;
}
cout << result;
}
int main()
{
string input;
getline(cin, input);
istringstream iss(input);
float num1, num2;
char op;
if (iss >> num1 >> op >> num2) {
Calculator(num1, op, num2);
} else {
cerr << "Invalid input format." << endl;
}
}
+ 3
Jerry Hobby No My Intension Is not to spam I just wanted it to reach question to everyone and i dont thing anything wrong in it am not spamming
+ 3
Shashikant Pandey
you should mark Jerry Hobby's answer as best. I only extended his suggestion... my code was only to show how istringstream could be used in a while loop.
+ 2
Please don't spam your tags like this. You asked a C++ question but added tags for every other word you could think of.
+ 2
Jerry Hobby Thank You Your Code Is Working As I Wanted
+ 2
//or a while loop for multiline input
#include <iostream>
#include <sstream>
using namespace std;
void Calculator(float num1, char op, float num2){
float result;
switch (op){
case '+':
result = num1 + num2; break;
case '-':
result = num1 - num2; break;
case '*':
result = num1 * num2; break;
case '/':
result = num1 / num2; break;
default:
cout << "Please Enter Correct Operation";
}
cout << result << '\n';
}
int main(){
string input;
float num1, num2;
char op;
istringstream iss;
while(getline(cin, input)){
iss.clear();
iss.str(input);
if(iss >> num1 >> op >> num2){
cout<<num1<<" "<<op<<" "<<num2<<" = ";
Calculator(num1, op, num2);
}
else
cerr << "Invalid input format." << endl;
}
}
/*
sample input
1 + 1
3 - 1
4 / 2
2 * 5
*/
+ 2
Bob_Li Thank You For Always Helping.
0
if you only want to process 1 equation, you can also write
cin >> num1 >> op >> num2;