如何使用C ++流优雅地读取整数? [英] How to read integers elegantly using C++ stream?

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

问题描述

我有一个以下格式的文件:

I have a file full of lines in this format:

1 - 2: 3

我只想使用C ++流加载数字。什么是最优雅的方式呢?

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.

推荐答案

你可以使用一个< a href =http://www.cplusplus.com/reference/std/locale/ =nofollow> 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()));

然后,当您读取文件时,它会将所有非数字转换为空格,数字。之后,你可以简单地使用你的正常转换来转换被读入int的内容。

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));

回复以下评论:

这是我做的工作

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;
}

这只把ints放到向量中,没什么了。之前它不工作的原因是两倍:

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可以容纳的数字是一个问题。我建议使用长号。

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆