Need some help with int/ double input error checkings

I'd like to put a condition for a 'double variable.' For example:

cin1:
double var1;
cin >> var1;

(How can I code if var1 is not a number, then execute)
cout << "The variable entered is not an executable number << endl;
cin.clear(); //clear and ignore value
cin.ignore(10, '/n');
goto cin1; // Go back to beginning

or something similar to allow the user to retype their input. I have tried putting the condition: if (!var1) as the condition before cout but using this code doesn't allow the integer 0 to be entered, I have also tried if (!var1 && var1 != 0) and this allows the value 0 to be stored in cin but executes incorrectly when a character or invalid integer is entered. Any help would be much appreciated.

Thank you
Easiest test would be.
1
2
3
4
5
double var1;
if (cin >> var1)
    // Valid probably
else
    // Definitely invalid 
allow the user to retype their input

Stop trying to write interactive programs with an interface designed for non-interactive input.

There are many permutations and embellishments you can apply but this is a bare-bones suggested solution.
A console application doesn't enable you to type back over incorrect input before you press return but that's possibly not what you meant.
In any case try it with this and see what happens :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

int main()
{
    double var{0};
    
    while( std::cout << "Enter an int: " and !(std::cin >> var) )
    {
        std::cin.clear();
        std::cin.ignore(1000, '\n');
        std::cout << "Invalid input. Please, try again\n";
    }
    
    std::cout << var << '\n';
    
    return 0;
}
// instead of '1000', the purist parameter is 'std::numeric_limits<std::streamsize>::max()' 
Thanks for the solutions, it worked
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
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <sstream>
#include <string>
using namespace std;


template<typename T> T input( string prompt = "" )
{
   T value;
   bool OK = false;
   string str; 
   while( !OK )
   {
      cout << prompt;
      getline( cin, str );
      stringstream ss( str );
      OK = ( ss >> value && !( ss >> str ) );    // a T and nothing but a T
      if ( !OK ) cout << "Invalid entry; try again\n";
   }
   return value;
}


template<> string input( string prompt )
{
   string value;
   cout << prompt;
   getline( cin, value );
   return value;
}


int main()
{
   double d = input<double>( "Enter a double: " );   cout << "You entered " << d << "\n\n";
   int    i = input<int   >( "Enter an int:   " );   cout << "You entered " << i << "\n\n";
   string s = input<string>( "Enter a string: " );   cout << "You entered " << s << "\n\n";
   char   c = input<char  >(                    );   cout << "You entered " << c << "\n\n";
}
Topic archived. No new replies allowed.