2012-07-05 28 views
3

我在C++練習中遇到問題。我在使用cin時在控制檯中出現新行

在練習中,我應該讓用戶輸入一個日期。

問題是,當我使用cin控制檯跳一行下來的時候我按回車,使之成爲像這樣的:

Enter date please: 12 

/23 

/2001 

代替:2001年12月23日

燦有人請幫我解決這個問題。

+0

你想讀給字符串或三個整數或在哪裏呢? – Blood 2012-07-05 21:41:23

+5

你可以將整個字符串讀作'12/23/2001',然後用'/'char分隔它。 – Tudor 2012-07-05 21:41:57

+2

除了在'/'上解析,因爲Tudor建議如果你更容易編碼,你能不能只讀3次日期,月份和年份的cin? – EdChum 2012-07-05 21:43:20

回答

6

你不說你如何使用cin來讀取日期。試試這個:

char ignored; 
int day, month, year; 
std::cin >> month >> ignored >> day >> ignored >> year; 

然後,當你運行你的程序,不按回車,直到你在整個日期類型。

4

Robᵩ有一個很好的答案,但我會擴展它。使用一個結構和一個重載的操作符,並檢查斜槓。

struct date { 
    int day; 
    int month; 
    int year; 
}; 
std::istream& operator>>(std::istream& in, date& obj) { 
    char ignored1, ignored2; 
    in >> obj.day>> ignored1 >> obj.month>> ignored2 >> obj.year; 
    if (ignored1!='/' || ignored2!='/') 
     in.setstate(in.rdstate() | std::ios::badbit); 
    return in; 
} 

如果您有streaming in literals代碼,這可以簡化爲:

std::istream& operator>>(std::istream& in, date& obj) { 
    return in >> obj.day>> '/' >> obj.month>> '/' >> obj.year; 
} 
+0

有趣的是文字流媒體;我從來沒想過那個。 – chris 2012-07-05 22:06:55

相關問題