簡體   English   中英

如果用戶輸入字符串,則從用戶中讀取\\ n和EOF?

[英]Reading in \n and EOF from the user, if user enters a string?

我想檢查用戶是否在他們輸入的字符串中輸入\\ n和EOF。 到目前為止,我已經嘗試過

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

確定有效提取比您想像的要簡單得多。 如果提取失敗,它將通過用於提取的輸入流的流狀態反映在程序中。 此外, 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."; } } 

以上僅是示例。 我沒有嘗試編譯它。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM