我想要做一个自定义的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;
}任何帮助都将不胜感激。
发布于 2016-08-16 19:45:34
这是个很好的问题。我不知道这是否可能。但是,我实现了一些不同的东西,通过使用一个名为>> 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;
}https://stackoverflow.com/questions/38982370
复制相似问题