Znalazłem ten link pod numerem http://www.parashift.com/c++-faq-lite/istream-and-ignore.htmlC++ Przykład: Nie jesteś w stanie zrozumieć, co się robi?
, który pokazuje "Jak mogę uzyskać std :: cin, aby pominąć nieprawidłowe znaki wejściowe?"
Use std::cin.clear() and std::cin.ignore().
#include <iostream>
#include <limits>
int main()
{
int age = 0;
while ((std::cout << "How old are you? ")
&& !(std::cin >> age)) {
std::cout << "That's not a number; ";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cout << "You are " << age << " years old\n";
...
}
Of course you can also print the error message when the input is out of range. For example, if you wanted the age to be between 1 and 200, you could change the while loop to:
...
while ((std::cout << "How old are you? ")
&& (!(std::cin >> age) || age < 1 || age > 200)) {
std::cout << "That's not a number between 1 and 200; ";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
...
Here's a sample run:
How old are you? foo
That's not a number between 1 and 200; How old are you? bar
That's not a number between 1 and 200; How old are you? -3
That's not a number between 1 and 200; How old are you? 0
That's not a number between 1 and 200; How old are you? 201
That's not a number between 1 and 200; How old are you? 2
You are 2 years old
Nie jestem w stanie uzyskać tego, jak to robi> Czy ktoś może wyjaśnić?
mam wątpliwości z:
while ((std::cout << "How old are you? ")
&& !(std::cin >> age))
Jak to jest sprawdzanie poprawny wpis? Chcę zapytać o wyrażenia "std :: cout < <" Ile masz lat? "I"! (Std :: cin >> age) ", zwróć true lub false, które są ANDed?
kolejna rzecz, która jest mylące jest użycie,
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Jakie są tam cel? Szukano w Google na temat tych funkcji, ale nadal nie jestem jasne. Szczególnie std::numeric_limits<std::streamsize>::max()
może ktoś pomóc? Dzięki
cin.clear() i cin.ignore() służy do zapobiegania CIN za pomijanie, (jeśli nie źle). Po raz pierwszy myślę, że to niewłaściwe pytanie. – cakil