[英]How to read a word from std::istringstream without assigning to a tmp variable through >>?
我有一個std::string line
,其中包含從文件讀取的一行文本。 然后,我創建一個istringstream
:
std::istringstream str(line);
閱讀這一行。 為了得到第一個詞,我這樣做:
std::string word;
str >> word;
有沒有一種方法可以直接從str
獲取單詞,而無需聲明中間變量word
?
例如,我想做類似的事情:
if (str.get_next_word_directly() == "yes")
do_something();
您必須使用命名變量來執行此操作; 可以提取到一個臨時文件,但是您無法識別該臨時文件,以對其調用operator==
。
一種選擇是將提取內容包裝在一個函數中,例如
std::string get_word(std::istream& is)
{
std::string word;
is >> word;
return word;
}
然后你可以寫
if( get_word(str) == "yes" )
NB。 對於C ++ 17,有一個建議允許使用str.get_word()
而不是get_word(str)
; 但現在您get_word(str)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.