【问题标题】:Ignore value read using input stream忽略使用输入流读取的值
【发布时间】:2019-05-05 20:28:12
【问题描述】:

有没有办法“转储”使用流读取的值而不将其读入虚拟变量?

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

【问题讨论】:

  • 应该可以定义一个空类,使用重载的格式化提取操作符,该操作符对类的临时实例的右值引用起作用。因此,对您的问题的简短回答似乎是:“是的,有办法做到这一点”。

标签: c++ io stream


【解决方案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';
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多