如何使用 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.
相关文章