Hello. Tell me, please, how to check the numbers in the loop, whether they are entered correctly. My method is not suitable, as the values ​​skip. How to deal with these "skips"?

int validIntInput() { int num; while(!(cin >> num)) { cin.clear(); cin.ignore((numeric_limits<std::streamsize>::max)(),'\n'); cout << "Wrong input. Please, try again: "; } return num; } 

When typing hex2, the function returns 1, while typing 1.2 - also 1.
I use this:

 for(int i = 0; i < COUNT; i++) numbers[i] = validIntInput(); 

Thank.

  • Read the whole line first, and then some strtoi64 () on what was read. - nitrocaster
  • @Regina, do not forget also about the correct handling of the end of the file ( cin.eof() == true ). - avp
  • @Flammable, if there is no other way out, you will have to do it in lines (although it seems to me that this is far from the best option) @avp, thanks, but alas, it did not work out :( - Regina

2 answers 2

@Regina , but what exactly does not work?

I would just change the input cycle a bit to detect EOF (or change the validIntInput prototype to bool validIntInput(int *) ).

Those. something like that:

  int i, iarray[n]; for (i = 0; i < n; i++) { iarray[i] = valid_int_input(); if (cin.eof()) break; } 

then the variable i after the completion of the input contains the number of actually entered elements of the array.

And the input function is:

 int valid_int_input () { while (1) { int n; if (cin >> n) return n; if (cin.eof()) return n; cin.clear(); string e; getline(cin, e); cout << "Invalid input. Ignore [" << e << "] Try again: "; } } 

In principle, it remains almost the same. Just add a refund on EOF.

  • one
    Thank!!! Now figured out and completed a little - Regina
  • though .. at input 1-123 2 elements of the array are written at once: 1 and -123 - Regina
  • 2
    This is already unrecoverable as part of element by element input. Both crosses and scanf () are considered normal -3 + 4-5 + 6 similar sequences. Here only reading with whole lines will help (getline ()) and independent parsing (for example, you can use strtol() ). - avp
 #include <iostream> #include <math.h> using namespace std; int main() { double a,b,g,u,x; cout<<"a="; cin>>a; cout<<"b="; cin>>b; cout<<"g="; cin>>g; cout<<"u="; cin>>u; cout<<"x="; cin>>x; double w,v,y; w=sin(u-2*g)+pow,sqrt(u+g),g); v=pow(g-2*u),2)-u*cos(g)/(3-4*u); y=log(tan(a*x))+sqrt(x,7)b*pow),2)/asin(x)-pow(a+x)); cout<<"w="<<w<<endl<<"v="<<v<<endl<<"y="<<y<<endl; system ("pause"); return 0; } 
  • @Andrey, To format the code, select it with the mouse and click on the {} button of the editor. - VladD