Итак, у меня есть несколько полей для заполнения цифрами. И если я попытаюсь заполнить ввод буквами (например, «сейчас» или «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;
}
'12nowshithappens' по существу трактуется как два поля:' 12' и 'nowshithappens'. Вы также можете ввести несколько чисел, разделенных пробелом, как в '1 2 3' - они будут с удовольствием использованы тремя различными вызовами' cin >> some_int_variable'. Если это не то, что вы хотите, используйте 'getline', чтобы прочитать одну целую строку в' std :: string', затем проанализируйте ее, используя любой синтаксис, который вы хотите потребовать. –