How to read integers elegantly using C++ stream?(如何使用 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:
- 我填满了9",但没有填满9"本身.我已将填充更改为:"
- 大于 int 可以容纳的数字是一个问题.我建议使用 long.
这篇关于如何使用 C++ 流优雅地读取整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 C++ 流优雅地读取整数?


基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01