Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //C++ Console Calculator
- //By Ben Bollinger
- #include <iostream>
- #include <vector>
- #include <string>
- //Split Method Declaration:
- std::vector<std::string> split(std::string uString, char oper);
- int main() {
- std::string statement;
- std::cout << "Enter statement (x to stop): ";
- std::cin >> statement;
- //Keep Program Running:
- while (statement != "x") {
- //Addition:
- if (strstr(statement.c_str(), "+")) {
- //Convert Split Method String Vec To Ints:
- int num1 = atoi(split(statement, '+')[0].c_str());
- int num2 = atoi(split(statement, '+')[1].c_str());
- //Calculate And Display Answer:
- int total = num1 + num2;
- std::cout << num1 << "+" << num2 << "=" << total << "\n";
- }
- //Subtraction:
- else if (strstr(statement.c_str(), "-")) {
- //Convert Split Method String Vec To Ints:
- int num1 = atoi(split(statement, '-')[0].c_str());
- int num2 = atoi(split(statement, '-')[1].c_str());
- //Calculate And Display Answer:
- int total = num1 - num2;
- std::cout << num1 << "-" << num2 << "=" << total << "\n";
- }
- //Multiplication:
- else if (strstr(statement.c_str(), "*")) {
- //Convert Split Method String Vec To Ints:
- int num1 = atoi(split(statement, '*')[0].c_str());
- int num2 = atoi(split(statement, '*')[1].c_str());
- //Calculate And Display Answer:
- int total = num1 * num2;
- std::cout << num1 << "*" << num2 << "=" << total << "\n";
- }
- //Division:
- else if (strstr(statement.c_str(), "/")) {
- //Convert Split Method String Vec To Ints:
- int num1 = atoi(split(statement, '/')[0].c_str());
- int num2 = atoi(split(statement, '/')[1].c_str());
- //Calculate And Display Answer:
- int total = num1 / num2;
- std::cout << num1 << "/" << num2 << "=" << total << "\n";
- }
- //Exception Handling:
- else {
- std::cout << "Invalid\n";
- }
- //Re-Ask To Continue:
- std::cout << "Enter statement (x to stop): ";
- std::cin >> statement;
- }
- //Pause Console:
- system("PAUSE");
- }
- //Split Method Definition:
- std::vector<std::string> split(std::string uString, char oper) {
- //Variables:
- std::vector<std::string> sVec;
- bool hit = false;
- std::string statement1 = "";
- std::string statement2 = "";
- //Loop Through All String Chars:
- for (int i = 0; i < uString.size(); i++) {
- if (uString.at(i) != oper && hit == false) {
- statement1 += uString.at(i);
- }
- //After Operator Add 1st Num:
- else if (uString.at(i) == oper) {
- sVec.push_back(statement1);
- hit = true;
- }
- //After Operator And First Num Create 2nd Num:
- else if (uString.at(i) != oper && hit == true) {
- statement2 += uString.at(i);
- }
- }
- //Add 2nd Num:
- sVec.push_back(statement2);
- return sVec;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement