manoli
manoli

Reputation: 1

getting numbers only for cin

trying to make a function that reliably and safely ask the user for the three components of a date – the day, the month & the year... i can get it to ask for the date... however i need to be able to make it so that you can only input numbers only, no letters and no mix of letters and numbers...

#include <iostream>

using namespace std;

    int Day;
    int Month;
    int Year;   

int GetYear(){
    cout << "Enter a Year > ";
    int nYear;
    cin >> nYear;
    cout << "Year: ";
    Year = nYear;
    return nYear;
}

int GetMonth(){
    cout << "\nEnter a Month > ";
    int nMonth;
    cin >> nMonth;
    cout << "Month: ";
    Month = nMonth;
    return nMonth;
}

int GetDay(int nMonth, int nYear){
    cout << "\nEnter a Day > ";
    int nDay;
    cin >> nDay;
    cout << "Day: ";
    Day = nDay;
    return nDay;
}

bool GetDate(int nDay, int nMonth, int nYear){
    cout << "\nDate: ";
    cout << nDay << "/" << nMonth << "/" << nYear << "\n";
    return 0; //GetDate(Day, Month, Year);
}

void main() {

    cout << GetYear();
    cout << GetMonth();
    cout << GetDay(Month, Year);
    cout << GetDate(Day, Month, Year);

    cout <<"Press Enter Key To Exist...";
    cin.ignore (numeric_limits<streamsize>::max(), '\n' ); 
    cin.get();
}

Upvotes: 0

Views: 1639

Answers (2)

wtm
wtm

Reputation: 1419

Maybe not a proper way... I use that in my school homework.

#include <iostream>
#include <stdio.h>
#include <conio.h>

int getInputNumber()
{
    int key;
    do
    {
        key = _getch();
    }while (key < '0' || key > '9');
    std::cout << key - '0';
    return key - '0';
}

int main()
{
    int n = getInputNumber() ;
    system("pause");
    return 0;
}

Also,just in windows

You need to write your own function,than you could input a number bigger than 9.

Upvotes: 1

Vikram.exe
Vikram.exe

Reputation: 4585

On a general note: It's not possible

When you invoke a program and use a shell (or a CMD prompt on windows) interface for taking inputs, all the input handling is done by the shell interface and it is not advisable to fiddle with it to accept only the required set of characters, because the shell is common for all the programs on your machine.

This is technically possible by implementing your own shell and replacing it with the default system shell, but let's not discuss it here and you should not do it :)

The best you can do is to verify the input for valid numbers. A simple ASCII value check will do it for you. You can also use some utility functions like atoi or strtoul to skip the invalid characters in the given input and just use the consecutive numeric digits.

Upvotes: 0

Related Questions