2014-01-25 55 views
0

我想檢查用戶是否在輸入的字符串中輸入\ n和EOF。到目前爲止,我試過如果用戶輸入字符串,從用戶讀入 n和EOF?

getline(cin, temp); 
if(cin.EOF())//tried and did not work 
    cout << "failed EOF"; 
if(temp[temp.size()] == '\n') 
    cout << "\n"; 
+0

不要使用'eof()',用布爾轉換來代替:'if(!cin)throw「一些讀取操作失敗」;' – Manu343726

+0

沒有'cin.EOF()' – PlasmaHH

+0

什麼是你使用這兩個條件的理由嗎? – 0x499602D2

回答

0

確定一個有效的提取比你想象的更直接。如果提取失敗,它將通過用於提取的輸入流的流狀態在程序中反映出來。不過,std::getline()返回流,當(隱式轉換爲布爾值時)流將檢查其流狀態的適當位。您可以利用此功能,幷包住提取在if聲明,將它的參數隱式轉換爲布爾值:

if (std::getline(std::cin, temp)) 

如果提取成功執行,則if語句將執行。如果你想通過流狀態響應用戶,您可以設置例外流掩蓋並檢查是否拋出異常:

if (std::getline(std::cin, temp)) 
{ 
    std::cout << "Extraction produced: " << temp << std::endl; 
} 

try { 
    std::cin.exceptions(std::ios_base::failbit | std::ios_base::eofbit); 
} 
catch (std::ios_base::failure&) 
{ 
    std::ios_base::iostate exceptions = std::cin.exceptions(); 

    if ((exceptions & std::ios_base::eofbit) && std::cin.eof()) 
    { 
     std::cout << "You've reached the end of the stream."; 
    } 
} 

以上只是一個例子。我沒有試圖編譯它。 :)