如何制作一个在真值之后退出的循环

时间:2014-10-24 12:08:34

标签: c++ loops

如果statement为false,我应该使用什么循环来再次输入用户输入值? 我的意思是一个月内最多有31天,所以如果用户输入32,程序会再次要求输入,如果语句为真,则循环退出。

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;
}

2 个答案:

答案 0 :(得分:1)

像这样:

#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;
}

您可以通过读取字符串行而不是整数来优化它。输入非整数后,当前代码将完全失败。可能的改进:

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
}

答案 1 :(得分:0)

解决问题的一般方法

#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;
}