C ++ cin.clear()和cin.ignore(...)问题

时间:2014-09-10 14:48:39

标签: c++ visual-c++ input cin

所以,我有几个字段用数字填写。如果我尝试用字母填写输入(例如' noway'或' gg1337' - 它会产生错误并要求提供有效数字(没有来自的字母。&# 39; 13'或' 1500000')。

但是有一个问题,如果我开始用数字填充输入然后我添加一些字母(例如' 12nowshithappens'),这会跳转到下一个输入字段,认为它是一个有效的数字,但在下一个输入字段中显示错误。

这是功能代码:

int appled()
{   
    cin >> appleds;
    while(cin.fail())
    {       
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(),'\n');
        cout << "An arror occured!\nPlease, enter a valid number: ";
        cin >> appleds;
    }
    return appleds;
}

如果我说错了 - 这是我测试程序的完整代码:)

// exZerry presents 

#include <iostream>
#include <conio.h>

int apples;
int fruit;
int oranges;
int x;
int appleds;
int orangeds;

using std::cout;
using std::cin;
using std::endl;
using std::numeric_limits;
using std::streamsize;

char newline = '\n';

bool ok;    
bool ok2;   
bool ok3;

int appled() //Function to receive 'apples' input
{   
    cin >> appleds;
    while(cin.fail())
    {       
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(),'\n');
        cout << "An arror occured!\nPlease, enter a valid number: ";
        cin >> appleds;
    }
    return appleds;
}
int oranged() //Function to receive 'oranges' input
{   
    cin >> orangeds;
    while(cin.fail())
    {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(),'\n');
        cout << "An arror occured!\nPlease, enter a valid number: ";        
        cin >> orangeds;
    }
    return orangeds;
}

int main()
{
    ok = ok2 = ok3 = false; //Some testing
    while(!ok2) //Actual program loop
    {       
        x = 0; // Dropping program restart.
        //cout << "-----------------------" << endl;
        //cout << "DEBUG MODE: " << x << endl;
        //cout << "-----------------------" << endl;
        cout << "=====================================================" << endl;
        cout << "Enter apples: ";
        apples = appled();
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(),'\n'); //Now we have apples
        cout << "Enter oranges: ";      
        apples = oranged();
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(),'\n'); //And now we have oranges
        cout << "\n=====================================================" << endl;
        cout << "Calculating..." << endl;
        cout << "=====================================================" << endl;
        fruit = apples + oranges;
        cout << "In total we have " << fruit << " fruit" << endl;
        cout << "=====================================================" << endl;
        cout << newline;
        //Option to go out or continue the loop
        //If you enter 1 - resets the program, any other char - exit
        cout << "Go out? (1 - 'No', Others - 'Yeap'):" << "  "; 
        cin >> x;
        cout << newline;
        // ok2 = true;
        if (x == 1) 
        {
            cout << "Continue the program..." << endl;
            //cout << "-----------------------" << endl;
            //cout << "DEBUG MODE: " << x << endl;
            //cout << "-----------------------" << endl;
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(),'\n');
            ok = false;
            ok3 = false;
            continue;
        }
        if (x == 0)
        {
            cout << "Shutting down the app..." << x << endl;
            //cout << "-----------------------" << endl;
            //cout << "DEBUG MODE: " << x << endl;
            //cout << "-----------------------" << endl;
            break;
        }
        else 
        {
            cout << "Shutting down the app..." << x << endl;
            //cout << "-----------------------" << endl;
            //cout << "DEBUG MODE: " << x << endl;
            //cout << "-----------------------" << endl;
            break;      
        }
    }
    cout << "Press any key to exit :D" << endl;
    getch();
    return 0;
}

2 个答案:

答案 0 :(得分:1)

您可以创建自己的方面来解析字符序列,就像添加无效字符序列一样。像这样:

class num_get : public std::num_get<char>
{
public:
    iter_type do_get( iter_type it, iter_type end, std::ios_base& str,
                      std::ios_base::iostate& err, long& v) const
    {
        auto& ctype = std::use_facet<std::ctype<char>>(str.getloc());
        it = std::num_get<char>::do_get(it, end, str, err, v);

        if (it != end && !(err & std::ios_base::failbit)
                      && ctype.is(ctype.alpha, *it))
            err |= std::ios_base::failbit;

        return it;
    }
};

现在您可以将其安装到您的信息流中:

std::locale orig(std::cin.getloc());
std::cin.imbue(std::locale(orig, new num_get));

while (!(std::cin >> appleds)) {
    // input was not entirely numeric
}

// input was entirely numeric

答案 1 :(得分:0)

所以我尝试了它,但感谢,Batmaaaan:D

添加完整的工作代码。它在做什么?简单:当你想要计算某些东西并且你显然不想在你的程序中计算字母时,这可能会帮助你做到这一点,同时使用C ++或其他任何东西。我想,对于每个人来说,有些基础知识=)

在Visual Studio 2012中制作和测试。花一些时间在一个地方收集每个代码的和平。

// exZerry presents 
// Apples & Oranges V2.1

#include <iostream>
#include <conio.h>

int apples;
int juce;
int oranges;
int x;
int appleds;
int orangeds;

using std::cout;
using std::cin;
using std::endl;
using std::numeric_limits;
using std::streamsize;
using std::locale;


char newline = '\n';

bool ok;    
bool ok2;   
bool ok3;

class num_get : public std::num_get<char>
{
public:
    iter_type do_get( iter_type it, iter_type end, std::ios_base& str,
                      std::ios_base::iostate& err, long& v) const
    {
        auto& ctype = std::use_facet<std::ctype<char>>(str.getloc());
        it = std::num_get<char>::do_get(it, end, str, err, v);

        if (it != end && !(err & std::ios_base::failbit)
                      && ctype.is(ctype.alpha, *it))
            err |= std::ios_base::failbit;

        return it;
    }
};

/*
int appled()
{   
    cin >> appleds;
    while(cin.fail())
    {       
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(),'\n');
        cout << "An arror occured!\nPlease, enter a valid number: ";
        cin >> appleds;
    }
    return appleds;
}
int oranged()
{   
    cin >> orangeds;
    while(cin.fail())
    {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(),'\n');
        cout << "An arror occured!\nPlease, enter a valid number: ";        
        cin >> orangeds;
    }
    return orangeds;
}
*/

int main()
{
    cout << "=====================================================" << endl;
    cout << "Welcome to exZerry's 'Apples & Oranges V2'" << endl;
    cout << "=====================================================" << endl;
    cout << newline;
    cout << newline;

    ok = ok2 = ok3 = false;
    while(!ok2) 
    {       
        x = 0;
        //cout << "-----------------------" << endl;
        //cout << "DEBUG MODE: " << x << endl;
        //cout << "-----------------------" << endl;
        cout << "=====================================================" << endl;
        cout << "Enter apples: ";
        // apples = appled();
        locale orig(cin.getloc());
        cin.imbue(locale(orig, new num_get));
        while (!(cin >> apples)) {
            cout << "An arror occured!\nPlease, enter a valid number: ";
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(),'\n');
        }
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(),'\n');
        cout << "Enter oranges: ";      
        // oranges = oranged();
        //std::locale orig(std::cin.getloc());
        cin.imbue(locale(orig, new num_get));
        while (!(cin >> oranges)) {
            cout << "An arror occured!\nPlease, enter a valid number: ";
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(),'\n');
        }
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(),'\n');
        cout << "\n=====================================================" << endl;
        cout << "Calculating..." << endl;
        cout << "=====================================================" << endl;
        juce = apples + oranges;
        cout << "In total we have " << juce << " fruit" << endl;
        cout << "=====================================================" << endl;
        cout << newline;
        cout << "Go out? (1 - 'No', Others - 'Yeap'):" << "  ";
        cin >> x;
        cout << newline;
        // ok2 = true;
        if (x == 1) 
        {
            cout << "Continue the program..." << endl;
            //cout << "-----------------------" << endl;
            //cout << "DEBUG MODE: " << x << endl;
            //cout << "-----------------------" << endl;
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(),'\n');
            ok = false;
            ok3 = false;
            continue;
        }
        if (x == 0)
        {
            cout << "Shutting down the app..." << x << endl;
            //cout << "-----------------------" << endl;
            //cout << "DEBUG MODE: " << x << endl;
            //cout << "-----------------------" << endl;
            break;
        }
        else 
        {
            cout << "Shutting down the app..." << x << endl;
            //cout << "-----------------------" << endl;
            //cout << "DEBUG MODE: " << x << endl;
            //cout << "-----------------------" << endl;
            break;      
        }
    }
    cout << "Press any key to exit :D" << endl;
    getch();
    return 0;
}