我想制作一个自定义的 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;
}
如有任何帮助,我们将不胜感激。
最佳答案
这是一个非常好的问题。我不知道是否可能。但我实现了一些不同的东西,通过使用名为 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;
}
关于c++ - 制作自定义 istream 操纵器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38982370/