IT 관련자료/C++

방어적 프로그래밍의 개념

elkein 2022. 2. 21. 20:56

    //semantic errors 논리오류
    int x;
    cin >> x;
    
    //5를 넣었을때도 아래 문구가 나오니 논리적오류 발생함.
    if (x >= 5)
        cout << "x is greater than 5" << endl;

 

    //violated assumption 사용자가 의도한 바와 다르게 사용

    string hello = "Hello, my name is sks";

    int ix;
    cin >> ix;
    cout << hello[ix] << endl;

 

=====================해결방안=============

>>조건을 넣어서 의도한 방향으로 사용하도록 코딩

    string hello = "Hello, my name is sks";

    cout << "Input from 0 to " << hello.size() - 1 << endl;

    int ix;
    cin >> ix;
    while (true)
    {
        if (ix >= 0 && ix <= hello.size() - 1)
        {
            cout << hello[ix] << endl;
            break;
        }
        else
        {
            cout << "plese try again" << endl;
            cin >> ix;
            
        }