C++ check whether is number is int/float

c++

Question

i'm new here. i found this site on google.

#include <iostream>

using namespace std;

void main() {

    // Declaration of Variable
    float num1=0.0,num2=0.0;

    // Getting information from users for number 1
    cout << "Please enter x-axis coordinate location : ";
    cin >> num1;

    // Getting information from users for number 2
    cout << "Please enter y-axis coordinate location : ";
    cin >> num2;

    cout << "You enter number 1 : " << num1 << " and number 2 : " << num2 <<endl;

I need something like, when users enter alphabetical characters, it would display an error says, you should enter numbers.

Any help greatly appreciated

1
8
4/24/2009 6:10:59 AM

First, to answer your question. This is actually very easy and you don't need to change much in your code:

cout << "Please enter x-axis coordinate location : " << flush;
if (!(cin >> num1)) {
    cout << "You did not enter a correct number!" << endl;
    // Leave the program, or do something appropriate:
    return 1;
}

This code basically checks whether the input was validly parsed as a floating point number – if that didn't happen, it signals an error.

Secondly, the return type of main must always be int, never void.

18
5/22/2009 10:52:05 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon