如何编写一个while循环,它接受两个整数并终止于' |'在c ++中?

时间:2015-06-20 14:10:30

标签: c++

我正在通过一本教科书进行自学。我可以做while循环没问题,但我不知道如何做终止字符。

以下是我现在所拥有的:

#include "../../std_lib_facilities.h" // Supplied by book author

int main()
{
    int ii = 0;
    int yy = 0;
    bool test = true;

    cout << "Enter two ints" << endl;

    while (test)
    {
        cin>>ii, cin>>yy;

        // this if statement doesn't work

        if (ii == '|' || yy == '|')
        { 
            test = false;
        }

        // this if statement catches all bad input, even the terminating '|'

        if (cin.fail())
        {  
            cout << "bad input";
            cin.clear();
            cin.ignore();
            continue;
        }
        else 
            cout << ii << yy << endl;

    }

    return 0;
}

2 个答案:

答案 0 :(得分:2)

如果你不熟悉它们,流可能会有点混乱。这是一个很大的话题,只是需要更多的研究。这是一个应该有用的例子,希望能让你开始。

int main(int argc, char* argv[])
{
    bool test = true;
    while ( test ) {
        std::cout << "Enter two integers> ";

        int x, y;
        // if this fails, stream is bad.
        // @note this will fail for any input which cannot be interpreted
        // as an integer value.
        if (std::cin >> x >> y) {
            std::cout << x << " " << y << std::endl;
        }
        else {
            // clear stream error state so we can read from it again.
            std::cin.clear();
            // check for terminating character; else unknown.
            if (std::cin.get() == '|')
                std::cout << "Terminator found, exiting." << std::endl;
            else
                std::cerr << "Error: bad input, exiting." << std::endl;
            // in either case the loop terminates.
            test = false;
        }
    }
    return 0;
}

希望这会有所帮助。祝你好运。

答案 1 :(得分:1)

在输入两个数字之前,使用cin.peek()功能如下:

 c=(cin >> ws).peek();
    if(c=='|')
    {
        cout<<"exiting";return 1;
    }

注意:(cin>>ws)是摆脱领先的空白。此外,c的类型为char

完整的代码现在看起来像这样:

int main()
{
    int ii = 0;
    int yy = 0;
    bool test = true;

    cout << "Enter two ints" << endl;

    while (test)
    {
        char c;
        c=(cin >> ws).peek();
        if(c=='|')
        {
            cout<<"exiting";return 1;
        }
        cin>>ii, cin>>yy;

        if (cin.fail())
        {
            cout << "bad input";
            cin.clear();
            cin.ignore();
            continue;
        }
        else
            cout << ii << yy << endl;

    }

    return 0;
}