有沒有辦法找到由 提取的令牌的開始位置istringstream::operator >>?
例如,我當前嘗試檢查失敗tellg()(在線運行):
string test = " first \" in \\\"quotes \" last";
istringstream strm(test);
while (!strm.eof()) {
string token;
auto startpos = strm.tellg();
strm >> quoted(token);
auto endpos = strm.tellg();
if (endpos == -1) endpos = test.length();
cout << token << ": " << startpos << " " << endpos << endl;
}
所以上面程式的輸出是:
first: 0 8
in "quotes : 8 29
last: 29 35
結束位置很好,但開始位置是通向標記的空白的開始。我想要的輸出是這樣的:
first: 3 8
in "quotes : 13 29
last: 31 35
這是帶有位置的測驗字串供參考:
1111111111222222222233333
01234567890123456789012345678901234 the end is -1
first " in \"quotes " last
^--------------------^-----^ the end positions i get and want
^-------^--------------------^------ the start positions i get
^---------^-----------------^---- the start positions i *want*
使用istringstream?時,是否有任何直接的方法來檢索此資訊?
uj5u.com熱心網友回復:
首先,請參閱為什么 iostream::eof 在回圈條件(即`while (!stream.eof())`)中被認為是錯誤的?
其次,您可以使用std::ws流操縱器在讀取下一個token值之前吞下空格,然后tellg()將報告您正在尋找的起始位置,例如:
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
...
string test = " first \" in \\\"quotes \" last";
istringstream strm(test);
while (strm >> ws) {
string token;
auto startpos = strm.tellg();
if (!(strm >> quoted(token)) break;
auto endpos = strm.tellg();
if (endpos == -1) endpos = test.length();
cout << token << ": " << startpos << " " << endpos << endl;
}
在線演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/370716.html
