如何使用 C++ 流优雅地读取整数?

How to read integers elegantly using C++ stream?(如何使用 C++ 流优雅地读取整数?)
本文介绍了如何使用 C++ 流优雅地读取整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样格式的全行文件:

I have a file full of lines in this format:

1 - 2: 3

我只想使用 C++ 流加载数字.最优雅的方法是什么?我只考虑 cin.get() 并检查每个字符是否为数字.

I want to only load numbers using C++ streams. Whats the most elegant way to do it? I only thought about cin.get() and checikng each char if it is number or not.

推荐答案

您可以使用 locale 更改在读取文件时从文件中读取的内容.也就是说,您将过滤掉所有非数字值:

You can use a locale to change what things are read from the file as it is being read. That is, you will filter out all non-numeric values:

struct numeric_only: std::ctype<char> 
{
    numeric_only(): std::ctype<char>(get_table()) {}

    static std::ctype_base::mask const* get_table()
    {
        static std::vector<std::ctype_base::mask> 
            rc(std::ctype<char>::table_size,std::ctype_base::space);

        std::fill(&rc['0'], &rc[':'], std::ctype_base::digit);
        return &rc[0];
    }
};

std::fstream myFile("foo.txt");
myfile.imbue(std::locale(std::locale(), new numeric_only()));

然后当您阅读文件时,它会将所有非数字转换为空格,而只留下数字.之后,您可以简单地使用常规转换将读取的内容转换为整数.

Then when you read your file, it'll convert all non digits to spaces while leaving you only the numbers. After that, you can simply use your normal conversions to transform what is being read into ints.

std::vector<int> intFromFile;
std::istream_iterator<int> myFileIter(myFile);
std::istream_iterator<int> eos;
std::copy(myFileIter, eos, std::back_inserter(intFromFile));

回复以下评论:

这是我为使其正常工作所做的工作

Here is what I did to get it to work

int main(int args, char** argv){
    std::fstream blah;
    blah.open("foo.txt", std::fstream::in);
    if(!blah.is_open()){
        std::cout << "no file";
        return 0;
    }
    blah.imbue(std::locale(std::locale(), new numeric_only()));

    std::vector<int> intFromFile;
    std::istream_iterator<int> myFileIter(blah);
    std::istream_iterator<int> eos;
    std::copy(myFileIter, eos, std::back_inserter(intFromFile));

   return 0;
}

这仅将整数放入向量中,仅此而已.之前它不起作用的原因有两个:

And this put only the ints into the vector, nothing more, nothing less. The reason it wasn't working before was two fold:

  1. 我填满了9",但没有填满9"本身.我已将填充更改为:"
  2. 大于 int 可以容纳的数字是一个问题.我建议使用 long.

这篇关于如何使用 C++ 流优雅地读取整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)