忽略使用输入流读取的值

时间:2018-12-04 11:57:59

标签: c++ io stream

是否有一种方法可以“转储”使用流读取的值而不将其读入虚拟变量?

例如,如果我有一个包含两个字符串和一个整数的文件,例如“ 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

1 个答案:

答案 0 :(得分:1)

std::basic_istream::ignore,但是它几乎没有用,因为:

  1. 它只能跳过一个特定的定界字符,而不跳过字符类(例如,任何空格)。
  2. 需要多次调用才能跳过一个单词。

您可以编写函数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';
}