Ho trovato questo collegamento a http://www.parashift.com/c++-faq-lite/istream-and-ignore.htmlEsempio C++: non è in grado di capire cosa si sta facendo?
che mostra "Come posso ottenere std :: cin per saltare caratteri di input non validi?"
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
Non riesco a capire come funziona> Qualcuno può spiegare per favore?
ho dei dubbi con:
while ((std::cout << "How old are you? ")
&& !(std::cin >> age))
Come mai controllando la voce valida? Voglio dire fare espressioni "std :: cout < <" Quanti anni hai? "E"! (Std :: cin >> età) ", restituisce true o false che sono ANDed?
un'altra cosa che è confondendo è l'utilizzo,
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Quali sono lì scopo? cercato su google su queste funzioni, ma ancora non mi è chiaro. in particolare, std::numeric_limits<std::streamsize>::max()
Può uno aiuto? Grazie
cin.clear() e cin.ignore() è per la prevenzione cin per essere saltato, (se non fa male). Per il primo momento, immagino che sia quello sbagliato che viene chiesto. – cakil