You need to clear the string from cin using cin.ignore, in addition to clearing the state of the stream (which cin.clear does).
, ( , , clearline, ) .
, , :
#include "clinput.hpp"
int main() {
using namespace std;
while (true) {
cout << "Enter a number (0 to exit): ";
int number;
if (cin >> number) {
cout << "Read " << number << '\n';
if (number == 0) {
break;
}
}
else {
if (cin.eof()) {
cerr << "Input failed due to EOF, exiting.\n";
return 1;
}
cerr << "Input failed, try again.\n";
clearline(cin);
}
}
return 0;
}
- ( ββ clinput_loop.cpp ), , (. "42 abc" ). , :
template<class Type, class Ch, class ChTr>
Type read(std::basic_istream<Ch,ChTr>& stream, Ch const* prompt) {
Type value;
if (could_not_get_input or more_of_line_left) {
throw std::runtime_error("...");
}
return value;
}
template<class Type, class Ch, class ChTr>
void read_into(
Type& value,
std::basic_istream<Ch,ChTr>& stream,
Ch const* prompt
) {
value = read<Type>(stream, prompt);
}
:
int n;
try {
read_into(n, std::cin, "Enter a number: ");
}
catch (std::runtime_error& e) {
raise;
}
cout << "Read " << n << '\n';
clearline, , , - ( , ):
#include <istream>
#include <limits>
template<class C, class T>
std::basic_istream<C,T>& clearline(std::basic_istream<C,T>& s) {
s.clear();
s.ignore(std::numeric_limits<std::streamsize>::max(), s.widen('\n'))
return s;
}
, , :
- std:: istream - typedef
std::basic_istream<char, std::char_traits<char> > - std:: wistream - typedef
std::basic_istream<wchar_t, std::char_traits<wchar_t> > - widen
'\n' L'\n' - char, wchar_t, basic_istream
clearline(stream) stream >> clearline, , std:: endl, std:: ws std:: boolalpha
Roger Pate