+ 1
1st Nov 2024, 2:51 AM
Shashikant Pandey
Shashikant Pandey - avatar
8 Réponses
0
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; } }
1st Nov 2024, 3:40 AM
Jerry Hobby
Jerry Hobby - avatar
+ 2
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
1st Nov 2024, 4:01 AM
Shashikant Pandey
Shashikant Pandey - avatar
+ 1
Please don't spam your tags like this. You asked a C++ question but added tags for every other word you could think of.
1st Nov 2024, 3:41 AM
Jerry Hobby
Jerry Hobby - avatar
+ 1
Jerry Hobby Thank You Your Code Is Working As I Wanted
1st Nov 2024, 4:03 AM
Shashikant Pandey
Shashikant Pandey - avatar
0
//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 */
1st Nov 2024, 4:56 AM
Bob_Li
Bob_Li - avatar
0
if you only want to process 1 equation, you can also write cin >> num1 >> op >> num2;
1st Nov 2024, 5:19 AM
Bob_Li
Bob_Li - avatar
0
Bob_Li Thank You For Always Helping.
1st Nov 2024, 5:43 AM
Shashikant Pandey
Shashikant Pandey - avatar
0
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.
1st Nov 2024, 6:31 AM
Bob_Li
Bob_Li - avatar