2012-05-04 42 views
0

試圖使一個功能,可靠和安全地要求用戶的三個 組件的日期 - 一天,一個月&年...我可以得到它要求的日期。 ..不過,我需要能夠讓這個你只能只輸入數字,沒有字母,沒有字母和數字的組合...獲取數字只爲cin

#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(); 
} 
+1

http://www2.research.att.com /~bs/bs_faq2.html#void-main。關於你的問題,以字符串形式讀入每一個字符串並確保它們都是數字,然後轉換爲int。另外,這是不是在課堂上有特殊原因? – chris

回答

0

在一般注:這是不可能

當您調用一個程序並使用shell(或windows上的CMD提示)接口進行輸入時,所有輸入處理都由shell接口完成,不是advisable來擺弄它只接受所需的一組字符,因爲shell對於您的機器上的所有程序都是通用的。

這在技術上是可以通過實現自己的外殼,並用默認的系統shell替換它,但我們在這裏不討論它,你不應該這樣做:)

你能做的最好的是驗證輸入爲有效數字。一個簡單的ASCII值檢查將爲你做。您還可以使用atoistrtoul等一些實用功能來跳過給定輸入中的無效字符,並使用連續的數字。

1

也許不是一個正確的方法... 我在我的學校作業中使用它。

#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; 
} 

此外,只需在窗口

你需要編寫自己的功能,比你可以輸入一個數大於9