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\n";
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 != '\n');
15         cout << "Sorry Please enter a number : " << endl;
16     }
17     cout << "I got your number : " << number << endl;
18 
19     return 0;
20 }

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM