[英]Extracting complete current line from std::istream
我正在掃描來自std::istream
的文本。 掃描已經在進行中,我想提取當前正在讀取的行(從頭到尾)。 此getCurrentLine()
function 不得修改std::istream
position。
我寫了這段代碼,我覺得很亂。 有一個更好的方法嗎? ( charStream_
是std::istream
)
std::string Scanner::getCurrentLine() const {
auto pos = charStream_.tellg();
// rewind until beginning of the line or stream
while (charStream_.peek() != '\n' && charStream_.tellg() != 0)
charStream_.unget();
// consume endline character
if (charStream_.peek() == '\n')
charStream_.get();
std::stringstream lineStream;
char c;
do {
c = static_cast<char>(charStream_.get());
lineStream << c;
} while (c != '\n' && c != EOF);
charStream_.seekg(pos);
return lineStream.str();
}
使用 function std::getline(std::cin, std::string)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.