我想制作一个自定义的istream
操纵器,它从输入中读取2个字符,然后从输入中跳过2个字符,直到它用完任何输入为止。
例如,如果我有这样的代码:
std::string str;
std::cin >> skipchar >> str;
skipchar
是我的操纵者,如果用户输入1122334455
,则str
应包含113355
。
这是我到目前为止所做的,我不知道应该在while循环条件中放入什么来使这段代码正常工作:
istream& skipchar(istream& stream)
{
char c;
while(1)
{
for (int i = 0; i < 2; ++i)
stream >> c;
for (int i = 0; i < 2; ++i)
stream.ignore(1, '\0');
}
return stream;
}
任何帮助都将不胜感激。
答案 0 :(得分:2)
这是一个非常好的问题。我不知道它是否可能。但是我实现了一些不同的东西,通过使用名为>> operator
的新类重载Skip2
,为您提供了所需的相同简短语法。这是代码(我非常喜欢写作!:-))
#include <iostream>
#include <string>
#include <istream>
#include <sstream>
using namespace std;
class Skip2 {
public:
string s;
};
istream &operator>>(istream &s, Skip2 &sk)
{
string str;
s >> str;
// build new string
ostringstream build;
int count = 0;
for (char ch : str) {
// a count "trick" to make skip every other 2 chars concise
if (count < 2) build << ch;
count = (count + 1) % 4;
}
// assign the built string to the var of the >> operator
sk.s = build.str();
// and of course, return this istream
return s;
}
int main()
{
istringstream s("1122334455");
Skip2 skip;
s >> skip;
cout << skip.s << endl;
return 0;
}
答案 1 :(得分:2)
这很棘手; istream操纵器不在流上作为“过滤器”操作,而是作为单次操作。标准(List<Guid> guids = ... // Creating by searching in Collection2 and deserializing
var collection = db.GetCollection<Collection1>("Collection1");
var result = collection.FindAsync(col => guids.Contains(col.Id)).ToListAsync();
,noskipws
等)提供的istream操纵器通过设置和清除流上的标志来完成它们的工作,因此它们只显示已经可用的功能。
但是,可以创建一个过滤 streambuf 包装hex
(或任何输入流)的streambuf并使用操纵器来安装或删除它:
cin
使用示例:
struct skipbuf : std::streambuf {
std::unique_ptr<std::streambuf> src;
int i;
char buf[4];
skipbuf(std::streambuf* src) : std::streambuf{*src}, src{src} {
setg(buf, buf + 2, buf + 2);
}
std::streambuf* unwrap() {
while (buf + i != gptr())
src->sputbackc(buf[--i]);
return src.release();
}
std::streambuf::int_type underflow() override {
setg(buf, buf, buf + std::min(i = src->sgetn(buf, 4), 2));
return i ? buf[0] : traits_type::eof();
}
};
std::istream& skipchar(std::istream& is) {
is.rdbuf(new skipbuf{is.rdbuf()});
return is;
}
std::istream& noskipchar(std::istream& is) {
if (auto* buf = dynamic_cast<skipbuf*>(is.rdbuf()))
delete (is.rdbuf(buf->unwrap()), buf);
return is;
}
预期输出(run it online):
int main() {
std::istringstream iss{"1122334455 hello"};
std::string s1, s2;
iss >> skipchar >> s1 >> noskipchar >> s2;
std::cout << s1 << ' ' << s2 << std::endl;
}