C++

C++ 콘솔 계산기

송현호 2024. 10. 5. 00:05

 

 

 

0으로 나눴을때 에러 메시지 출력

 

#include <iostream>
#include "Calculator.h"
using namespace std;

int main()
{
    double x = 0.0;
    double y = 0.0;
    double result = 0.0;
    char oper = '+';

    cout << "Calculator Console Application" << endl << endl;
    cout << "Please enter the operation to perform. Format: a+b | a-b | a*b | a/b"
        << endl;

    Calculator c;
    while (true)
    {
        cin >> x >> oper >> y;
        if (oper == '/' && y == 0) {
            cout << "Error : 숫자 0으로 나눌 수 없습니다.";
        }
        else {
            result = c.Calculate(x, oper, y);
        }
        
        cout << "Result " << "of " << x << oper << y << " is: " << result << endl;
    }

    return 0;
}

 

 

한글도 입력가능하도록 수정해보자

 

#include <iostream>
#include "Calculator.h"
using namespace std;

int main()
{
    double x = 0.0;
    double y = 0.0;
    double result = 0.0;
    char oper = '+';

    cout << "Calculator Console Application" << endl << endl;
    cout << "Please enter the operation to perform. Format: a+b | a-b | a*b | a/b"
        << endl;

    Calculator c;
    while (true)
    {
        if (!(cin >> x >> oper >> y)) {
            cout << "잘못된 입력입니다.";
            continue;
        }
        if (oper == '/' && y == 0) {
            cout << "Error : 숫자 0으로 나눌 수 없습니다.";
        }
        else {
            result = c.Calculate(x, oper, y);
        }
        
        cout << "Result " << "of " << x << oper << y << " is: " << result << endl;
    }

    return 0;
}

 

 

https://dntworry-behappy.tistory.com/2

 

[C++] std::cin.ignore(), std::cin.clear(), std::cin.fail() 함수

cin에서 입력을 받을 때 원하지 않는 값이 입력으로 들어올 때가 있다. 이유는 입력버퍼에 해당 값이 아직 남아있기 때문인데, 이때 위 함수들을 사용할 수 있다. 1. cin.ignore() 첫번째, cin.ignore 함

dntworry-behappy.tistory.com

 

 

플래그를 초기화하고, 입력 버퍼를 비워주었다.

 

#include <iostream>
#include "Calculator.h"
using namespace std;

int main()
{
    double x = 0.0;
    double y = 0.0;
    double result = 0.0;
    char oper = '+';

    cout << "Calculator Console Application" << endl << endl;
    cout << "Please enter the operation to perform. Format: a+b | a-b | a*b | a/b"
        << endl;

    Calculator c;
    while (true)
    {
        cin >> x >> oper >> y;
        if (cin.fail()) {
            cout << "Error : 잘못된 입력입니다." << '\n';
            cin.clear();
            cin.ignore(10000, '\n');
            continue;
        }
        if (oper == '/' && y == 0) {
            cout << "Error : 숫자 0으로 나눌 수 없습니다.";
        }
        else {
            result = c.Calculate(x, oper, y);
        }
        
        cout << "Result " << "of " << x << oper << y << " is: " << result << endl;
    }

    return 0;
}

'C++' 카테고리의 다른 글

RAII, 스마트 포인터  (1) 2024.10.02
Hello World!  (1) 2024.10.02