How to make cin take only numbers
这是代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | double enter_number() { double number; while(1) { cin>>number; if(cin.fail()) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\ '); cout <<"Invalid input" << endl; } else break; cout<<"Try again"<<endl; } return number; } |
我的问题是,当我输入类似1x的内容时,将1用作输入而没有注意到留给下一次运行的字符。
有什么办法可以使其与任何实数一起工作,例如1.8?
当cin遇到输入时,它无法正确读入指定的变量(例如,将字符输入到整数变量中),它将进入错误状态,并将输入保留在缓冲区中。
您必须做一些事情才能正确处理此情况。
以下代码提供了完成这三件事的众多方法之一。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #include<iostream> #include<limits> using namespace std; int main() { cout <<"Enter an int:"; int x = 0; while(!(cin >> x)){ cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\ '); cout <<"Invalid input. Try again:"; } cout <<"You enterd:" << x << endl; } |
您可以向cin.ignore传递一个较大的值(例如1000),并且出于所有实际目的,它的行为可能完全相同。
您也可以在尝试输入后测试cin并以这种方式进行处理,例如
if(!cin){//清除错误}。
查看istream参考以了解其他处理流状态的成员函数:http://cplusplus.com/reference/iostream/istream/
我将使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include <string> #include <sstream> int main() { std::string line; double d; while (std::getline(std::cin, line)) { std::stringstream ss(line); if (ss >> d) { if (ss.eof()) { // Success break; } } std::cout <<"Error!" << std::endl; } std::cout <<"Finally:" << d << std::endl; } |
我希望使用以下代码。在许多可以清除我们这个问题的代码中,我认为这是我在网上找到的最合适的代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #include <iostream> #include <limits> using namespace std; int main(){ int n; while(!(cin >> n)) { cin.clear(); // to clear the buffer memory cin.ignore(numeric_limits<streamsize>::max(), '\ '); cout <<"Please enter a valid integer!"; } cout <<"Your Integer:" << n << endl; return 0; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #include<iostream> #include<cstdlib> #include<cstring> using namespace std; int get_int(void); int main() { puts("Enter a number"); cout<<"The integer is"<<get_int()<<endl; return 0; } int get_int(void) { char str[20]; char* end; int num; do{ fgets(str,20,stdin); str[strlen(str)-1]='\\0'; num=strtol(str,&end,10); if(!(*end)) return num; else { puts("Please enter a valid integer"); num=0; } }while(num==0); } |
这对于任何整数都适用。它甚至可以检查您是否在整数后面输入空格或其他任何字符。唯一的问题是它不使用