[英]C++ getline and gcount
假設我有一個std::istream
指向以下內容(換行符是'\\n'
字符):
12345678
9
並運行以下代碼:
std::istream & is = ...
char buff[9];
is.getline(buff, 9);
int n = is.gcount();
現在n == 8
和strcmp(buff, "12345678") == 0
。 問題是,我怎么知道我讀了整行而不是某些行?
相反,如果蒸汽指向以下內容:
123456789
0
並且執行了相同的代碼,我仍然在同一行上。 如何區分這兩種情況?
使用std::string
和免費的std::getline
函數:
#include <istream>
#include <string>
// ...
std::istream & is = ...;
std::string line;
while (std::getline(is, line))
{
// process line
}
答案的關鍵在於您的問題
is.getline(buff, 9);
int n = is.gcount();
Now n == 8
根據getline的參考 ,它最多可以提取n - 1
字符-在您的情況下,最多可以提取8個字符。這有點誤導,因為如果第n個字符是定界符,則也將提取該字符(但不會將其復制到緩沖區)。 更重要的是,如果您在到達n
字符之前尚未到達定界符,則該內容與之相關:
If the function stops reading because this size (n) is reached,
the failbit internal flag is set
因此,簡而言之,如果設置了失敗位,則您仍在同一行上(並且必須清除狀態才能繼續處理istream)。 有時,eof也會設置失敗位。 因此,您可能想檢查狀態是否為故障位,而僅是故障位:
if ( is.rdstate() == std::ios::failbit ) {
std::cout << "Filled the buffer, but did NOT finish the line\n";
is.clear();
}
閱讀下一個字符。 如果是換行符,則您已讀取該行上的所有數據。
順便說一句,流行的用法是將整行,直到換行,讀入std::string
,然后處理該字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.