I wrote a program to terminate reading into an array of double when an invalid input is made.
This is the program,
#include<iostream>
int main()
{
using namespace std;
double val[10];
int i=0;
cout<<"You can enter up to 10 values.\n";
cout<<"Enter value "<<i+1<<": ";
int count=0;
while(cin>>val[i]&&i<10)
{ count++;
i++;
cout<<"\nEnter value "<<i+1<<": ";
}
cout<<"Process terminated\n";
cout<<"No. of values read: "<<count;
return 0;
}
This works just fine.
For example, if a enter, say "x",where a numeric input is required, the loop ends and further input is not taken.
Sample run:
You can enter up to 10 values.
Enter value 1: 23.5
Enter value 2: x
Process terminated
No. of values read: 1
But when i enter, for example, "22.4dsa", the input is still read till 22.4 and leaves the rest in the buffer, which is automatically read by the next element in my array.I don't want this to happen, as i want "22.4dsa" to be treated as invalid as a whole.
Sample run:
You can enter up to 10 values.
Enter value 1: 23.5
Enter value 2: 22.4dsa
Enter value 3: Process terminated
No. of values read: 2
I want 'No. of values read:' to be '1' as "22.4dsa" is invalid for me. How do i do that?
I hope my question is clear. Thank you