Question:
Is it possible to make it so that when a number is entered, the program is executed until a key combination is entered, for example Ctrl + Z, but at the same time a check is performed, if a character is entered, then the program displays an error message and re-asks to enter the number?
while (true) {
cout << "Input your number: ";
cin >> value;
if (!cin.good())
{
if (value == 'q')
exit(0);
else
{
while (!cin)
{
cin.clear();
while (cin.get() != '\n')
continue;
cout << "Error!\n";
cout << "Input your number: ";
continue;
}
}
}
Answer:
#include <iostream>
#include <string>
using namespace std;
int main(){
string stringValue;
double numericValue;
while (true) {
cout << "Input your number: ";
if ( std::cin >> numericValue ) {
// если введено число продолжаем ввод
} else {
// пробуем считать строку из введенного значения
std::cin.clear(); // очищаем буфер!
if ((std::cin >> stringValue) ) {
if (stringValue == "q") {
exit(0);
} else {
cout << "Enter numner or 'q' for exit:" << endl;
}
}
}
}
}