0

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

Codor
  • 17,447
  • 9
  • 29
  • 56
utkarsh
  • 1
  • 1
  • 3
    Read the input as a string, and then try to convert it to a number. There are two functions ([`std::stod`](http://en.cppreference.com/w/cpp/string/basic_string/stof) and [`std::strtod`](http://en.cppreference.com/w/cpp/string/byte/strtof)) which can help you with that. They both have functionality to help you check if the whole string was used in the conversion or not. – Some programmer dude Mar 28 '17 at 11:18
  • On an unrelated not you have a flaw in your loop condition. This flaw can lead you to write out of bounds of the `val` array. – Some programmer dude Mar 28 '17 at 11:21
  • Okay let's say i allow reading input till '22.4' .Is it possible to discard rest of the part i.e. 'dsa' , so that it doesn't get read to the next array element? If yes, how? And what kind of flaw, please tell – utkarsh Mar 28 '17 at 11:25
  • That's why you read it as a string. If you use `>>` then it will read the "string" to the next white-space. If you want to be even more sure there's nothing left on the line, then use [`std::getline`](http://en.cppreference.com/w/cpp/string/basic_string/getline) to read the whole line. – Some programmer dude Mar 28 '17 at 11:28
  • Okay! and what kind of flaw were you talking about ? – utkarsh Mar 28 '17 at 11:33
  • Your loop condition will read *11* values before noticing that `i < 10` is false. Change the order of the sub-expressions in the condition. – Some programmer dude Mar 28 '17 at 11:34
  • oh okay, will do that. Thankyou – utkarsh Mar 28 '17 at 11:36

0 Answers0