簡體   English   中英

C ++ cin.clear()和cin.ignore(…)問題

[英]C++ cin.clear() and cin.ignore(…) issue

因此,我有幾個字段要用數字填寫。 如果我嘗試用字母(例如'noway'或'gg1337')填充輸入內容,則會出錯,並要求輸入有效的數字(例如,例如'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;
}

您可以使自己解析諸如此類的字符序列的構面無效。 像這樣:

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

所以我嘗試了,並且成功了,謝謝,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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM