获取istringstream token起始位置
Obtaining start position of istringstream token
有没有办法找到istringstream::operator >>
提取的令牌的起始位置?
例如,我当前尝试检查 tellg()
(run online) 失败:
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
时,是否有任何直接的方法来检索此信息 ?
先看Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?
其次,您可以使用 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;
}
有没有办法找到istringstream::operator >>
提取的令牌的起始位置?
例如,我当前尝试检查 tellg()
(run online) 失败:
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
时,是否有任何直接的方法来检索此信息 ?
先看Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?
其次,您可以使用 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;
}