2014-09-10 4 views
1

Итак, у меня есть несколько полей для заполнения цифрами. И если я попытаюсь заполнить ввод буквами (например, «сейчас» или «gg1337» - он делает ошибку и запрашивает действительное число (без букв для ex. '13' или '1500000').C++ cin.clear() и cin.ignore (...) issue

НО есть одна проблема, если я начну заполнять ввод цифрами, а затем добавляю несколько букв (например, «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; 
} 
+0

'12nowshithappens' по существу трактуется как два поля:' 12' и 'nowshithappens'. Вы также можете ввести несколько чисел, разделенных пробелом, как в '1 2 3' - они будут с удовольствием использованы тремя различными вызовами' cin >> some_int_variable'. Если это не то, что вы хотите, используйте 'getline', чтобы прочитать одну целую строку в' std :: string', затем проанализируйте ее, используя любой синтаксис, который вы хотите потребовать. –

ответ

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 
0

Так что я попробовал, и она работала, спасибо, Batmaaaan: D

Добавление полный рабочий код. Что он делает? Простой: когда вы хотите что-то посчитать, и вы, очевидно, не хотите считать буквы в своей программе, это может помочь вам это сделать, в то время как St ++ 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; 
} 
Смежные вопросы