是否有可能从输入流中"丢弃"读取值?

pin*_*gul 3 c++ inputstream input cin istream

我用列中的数据处理一些数据,比如

1 -0.004002415458937208 0.0035676328502415523
2 -0.004002415796209478 0.0035676331876702957
....
Run Code Online (Sandbox Code Playgroud)

我只对最后两个值感兴趣.我通常觉得读取值很方便:

std::ifstream file(file_name);
double a, b;
for (lines) {
    //      | throwing away the first value by reading it to `a`
    file >> a >> a >> b;
    store(a, b);
}
Run Code Online (Sandbox Code Playgroud)

我不确定这对其他人有多可读,当数据结构未知时,可能会将其视为错误.我能以某种方式使它看起来更明确,我真的想扔掉第一个读取值吗?

我想要一些这方面的东西,但没有任何效果:

file >> double() >> a >> b; // I hoped I could create some r-value kind of thing and discard the data in there
file >> NULL >> a >> b;
Run Code Online (Sandbox Code Playgroud)

jag*_*ire 9

如果你不想显式地创建一个被忽略的变量,并且你觉得通过调用操作流明确地忽略了这个值太冗长了,你可以利用operator>>重载来std::istream获取一个std::istream&(*)(std::istream&)函数指针:

template <typename CharT>
std::basic_istream<CharT>& ignore(std::basic_istream<CharT>& in){
    std::string ignoredValue;
    return in >> ignoredValue;
}
Run Code Online (Sandbox Code Playgroud)

使用方式如下:

std::cin >> ignore >> a >> b;
Run Code Online (Sandbox Code Playgroud)

如果你想验证它是一个可以读入类型的表单,你可以提供一个额外的模板参数来指定被忽略值的类型:

// default arguments to allow use of ignore without explicit type
template <typename T = std::string, typename CharT = char>
std::basic_istream<CharT>& ignore(std::basic_istream<CharT>& in){
    T ignoredValue;
    return in >> ignoredValue;
}
Run Code Online (Sandbox Code Playgroud)

使用方式如下:

std::cin >> ignore >> a >> b;
// and
std::cin >> ignore<int> >> a >> b;
Run Code Online (Sandbox Code Playgroud)

关于coliru的演示


Dim*_*_ov 8

你可以用std::istream::ignore.

例如:

file.ignore(std::numeric_limits<std::streamsize>::max(), ' '); //columns are separated with space so passing it as the delimiter.
file >> a >> b;
Run Code Online (Sandbox Code Playgroud)