C++ cin.clear()使用示例

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 int main()
 5 {
 6     int number;
 7     while (cout << "Enter a number : " && !(cin>>number))
 8     {
 9         cin.clear();
10         string line;
11         getline(cin, line);
12         cout << "I am sorry, but '" << line << "' is not a number
";
13     }
14     cout << "I got your number : " << number << endl;
15 
16 
17     return 0;
18 }

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 int main()
 5 {
 6     int number;
 7     while (cout << "Enter a number : " && !(cin>>number))
 8     {
 9         cin.clear();
10         char ch;
11         do
12         {
13             cin.get(ch);
14         } while(ch != '
');
15         cout << "Sorry Please enter a number : " << endl;
16     }
17     cout << "I got your number : " << number << endl;
18 
19     return 0;
20 }

 

原文地址:https://www.cnblogs.com/zuosy/p/8533639.html