是否有一种方法可以“转储”使用流读取的值而不将其读入虚拟变量?
例如,如果我有一个包含两个字符串和一个整数的文件,例如“ foo.txt”如下所示:
foo bar 6
foofoo barbar 8
是否可以执行以下操作:
std::string str;
int i;
std::ifstream file("foo.txt");
file >> str >> nullptr >> i;
并且之后有str = "foo"
和i = 6
?
答案 0 :(得分:1)
有std::basic_istream::ignore
,但是它几乎没有用,因为:
您可以编写函数ignore_word(std::istream& s)
:
std::istream& ignore_word(std::istream& s) {
while(s && std::isspace(s.peek()))
s.get();
while(s && !std::isspace(s.peek()))
s.get();
return s;
}
int main() {
std::istringstream s("foo bar 6");
std::string foo;
int i;
s >> foo;
ignore_word(s);
s >> i;
std::cout << foo << ' ' << i << '\n';
}