-5

What loop should I use to make user input value again if statement is false? I mean there are max 31 days in a month so if user inputs 32, program will ask to type again, and if statement is true then loop exits.

int main()
{
    int day;
    cout<<"Enter a day"<<endl;
    cin>>day;
        if(day<32){
    // class Input
    Input inObject(day);
    // printInput(){cout<<"Today is the "<<input<<endl;}
    inObject.printInput();
    }else{
        cout<<"Incorrect day! Enter again."<<endl;
    }
    return 0;
}
MadCloud
  • 3
  • 1

2 Answers2

1

Like so:

#include <cstdlib>
#include <iostream>

int main()
{
    for (int day; std::cout << "Enter a day: " && std::cin >> day; )
    {
        if (day > 31)
        {
            std::cout << "Invalid day, try again.\n";
            continue;
        }

        Input inObject(day);
        // ...
        return EXIT_SUCCESS;
    }

    std::cout << "Premature end of input!\n";
    return EXIT_FAILURE;
}

You can refine this by reading string lines rather than ints. The present code will fail entirely once you enter a non-integer. A possible improvement:

for (std::string line;
     std::cout << "Enter a day: " && std::getline(std::cin, line); )
{
    std::istringstream iss(line);
    int day;
    if (!(iss >> day >> std::ws) || iss.get() != EOF || day > 31)
    {
        /*error*/
        continue;
    }

    // as before
}
Jan Hudec
  • 73,652
  • 13
  • 125
  • 172
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
0

A generalized approach to your problem

#include <iostream>
#include <string>
#include <functional>

template<typename Ty>
struct CheckedIn
{
    CheckedIn(std::function<bool(Ty)> fn): m_fn(fn) {}
    CheckedIn(std::string prompt, std::function<bool(Ty)> fn):m_prompt(prompt), m_fn(fn) {}
    CheckedIn(std::string prompt, std::function<bool(Ty)> fn, std::string errormsg):
        m_prompt(prompt), m_errormsg(errormsg), m_fn(fn) {}
    CheckedIn& operator>>(Ty _in)
    {
        do
        {
            std::cout << m_prompt;
            std::cin >> _in;
        } while(m_fn(_in) && std::cout<<(m_errormsg==""?"Invalid Input":m_errormsg));
        return *this;
    }

private:
    std::function<bool(Ty)> m_fn;
    std::string m_prompt;
    std::string m_errormsg;
};

int main()
{
    int day = int();
    CheckedIn<int>("Enter a day: ", 
                   []( int day){return bool(day > 31); },
                   "Invalid day, try again.\n") >> day;
    return 0;
}
Abhijit
  • 62,056
  • 18
  • 131
  • 204